Search code examples
sqlsql-serversql-server-2014

Combining these two SQL Queries


i'm having troubling combining these two SQL queries. I have this original query which selects data from two tables, the related columns being Tasks.CustomerID and Customers.CustomerID. It's basically Tasks.* + Customers.Name

ALTER PROCEDURE [dbo].[SP_SelectTasksandName]
AS
SELECT TASKS.CustomerID, TASKS.DateCreation, TASKS.DateFinish, TASKS.Description, TASKS.Fees, TASKS.Hours, TASKS.InvoiceNum, TASKS.PaymentMethod,
        TASKS.Status, TASKS.TaskID, CUSTOMERS.Name
FROM TASKS, CUSTOMERS
WHERE (TASKS.CustomerID LIKE CUSTOMERS.CustomerID)

This works, but I've now been asked to limit this query to a specified amount of rows. I found this code which worked well for my other, simpler queries, but I can't seem to use it correctly with this query. This Limit code is below. (i.e all rows > @low && rows <= @high)

SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY CustomerID) as row FROM CUSTOMERS
    ) a WHERE ((a.row > @low and a.row <= @high) 

This is the closest i've gotten, but i'm stuck here.

SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY TASKS.CustomerID) as row FROM 
        (SELECT TASKS.CustomerID, TASKS.DateCreation, TASKS.DateFinish, TASKS.Description, TASKS.Fees, TASKS.Hours, TASKS.InvoiceNum, TASKS.PaymentMethod,
                TASKS.Status, TASKS.TaskID, CUSTOMERS.Name
        FROM TASKS, CUSTOMERS
        WHERE (TASKS.CustomerID LIKE CUSTOMERS.CustomerID))

) a WHERE (a.row > @low and a.row <= @high)

With an error "expecting as id or quoted id" on the first bracket on the last line.

Sorry for the noob question, appreciate any help you guys can give.


Solution

  • Never use commas in the FROM clause. Always use proper, explicit JOIN syntax.

    The query you are looking for can be written as:

    SELECT tc.*
    FROM (SELECT t.CustomerID, t.DateCreation, t.DateFinish, t.Description, 
                 t.Fees, t.Hours, t.InvoiceNum, t.PaymentMethod,
                 t.Status, t.TaskID, c.Name,
                 ROW_NUMBER() OVER (ORDER BY t.CustomerID) as seqnum
            FROM TASKS t JOIN
                 CUSTOMERS c
                 ON t.CustomerID = c.CustomerID
         ) tc
    WHERE tc.seqnum > @low ANDtc.seqnum <= @high