SQL Server SQL nested SELECT statements [duplicate]

zwghvu4y  于 2023-03-07  发布在  其他
关注(0)|答案(2)|浏览(136)

This question already has answers here:

Incorrect syntax near ')' in SQL (2 answers)
Closed 4 days ago.

I am trying to select only certain columns from a table but need to read in these columns based on conditions of other columns that I DON'T want to include in the final output - if that makes any sense. I'm sure it's probably pretty simple but can't see what's wrong.

Hopefully my SQL query will clear up what I'm trying to do:

SELECT 
    dateOfBooking, amORpm, conferenceRoomID, noDelegates, cateringInfo
    , allergyInfo, specialAccessInfo, bottledWaterNeeded, projectorNeeded
    , lecternNeeded
FROM (
    SELECT *
    FROM dbo.tableBookingSlots
    WHERE bookingID = @bookingID
);
toiithl6

toiithl61#

You should use CTE in this case

WITH data AS (
        SELECT * FROM  dbo.tableBookingSlots WHERE bookingID = @bookingID
    ) SELECT 
dateOfBooking, amORpm, conferenceRoomID, noDelegates, cateringInfo, allergyInfo, specialAccessInfo, bottledWaterNeeded, projectorNeeded, lecternNeeded
FROM data

OR just do it in that way without subquery

SELECT 
dateOfBooking, amORpm, conferenceRoomID, noDelegates, cateringInfo, allergyInfo, specialAccessInfo, bottledWaterNeeded, projectorNeeded, lecternNeeded
FROM dbo.tableBookingSlots WHERE bookingID = @bookingID
oogrdqng

oogrdqng2#

Your query and pattern is fine, but your subquery needs an alias:

SELECT 
    dateOfBooking, amORpm, conferenceRoomID, noDelegates, cateringInfo,
    allergyInfo, specialAccessInfo, bottledWaterNeeded, projectorNeeded,
    lecternNeeded
FROM (
    SELECT *
    FROM dbo.tableBookingSlots
    WHERE bookingID = @bookingID
) t;

相关问题