Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Nested SELECT Syntax error 1

Status
Not open for further replies.

ronspree

Technical User
May 3, 2003
103
PH
I'm using SQL Server 7, and have something like this in a stored procedure (this is a simplified version):

Code:
SELECT EmployeeID, Lastname FROM (SELECT Employees.ID AS EmployeeID, Employees.Lastname FROM Employees)
The error is: Line 7: Incorrect syntax near ')'.

Strangely, the following will work:

Code:
SELECT EmployeeID, Lastname FROM (SELECT Employees.ID AS EmployeeID, Employees.Lastname FROM Employees) GO
But the following will not:
Code:
SELECT EmployeeID, Lastname FROM (SELECT Employees.ID AS EmployeeID, Employees.Lastname FROM Employees) 
GO
Strange. Anyway, I must be missing something here. What is the correct syntax for my case?

 
What is it you are trying to accomplish here? This syntax would be incorrect unless you use an IN statment. But it is unclear what you are trying to do.

Jim
 
Its something like:
Code:
Create Procedure strDatasheet
@PeriodID int
AS
SELECT EmployeeID, SUM(WorkEarnings)
FROM
(SELECT EmployeeID, Rate * Quantity AS WorkEarnings From WeeklyEarnings WHERE PeriodID = @PeriodID
UNION ALL
SELECT EmployeeID, Amount AS WorkEarnings FROM OtherEarnings
WHERE PeriodID = @PeriodID)
GROUP BY EmployeeID

The problem with the inner Select statement is that multiple instances of EmployeeID are present because of the UNION ALL. So to group EmployeeID, I nested it inside another select with the GROUP BY clause.
 
Derived tables must be have a name

Code:
select <...>
 from (select ... ) dt

In your second example GO was interpreted as a name for the derived table.
 
Swamp, so that's what its called: Derived tables. Searching for "derived tables" on the BOL confirmed your answer: derived tables should have a name. Thank you very much. My code should have been:
Code:
SELECT EmployeeID, Lastname FROM (SELECT Employees.ID AS EmployeeID, Employees.Lastname FROM Employees) AS DerivedEmployeesTable
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top