I have 2 tables UserSession and Sale.
Table User has 4 columns, namely UserID, UserSessionID, SessionOpenDate and SessionCloseDate.
Table Sale has 2 columns, which are price, cost, userID and CompletedDate.
When a user logs in, a new row is created in the User table, where the user’s login timestamp will be saved in the SessionOpenDate and a new UserSessionID will be assigned to the session. When the user logs off, the log off timestamp will be be saved in SessionCloseDate.
When the user is still logged in, the user can make some sale and the sale information is saved in the Sale table. The timestamp when the sale is finalized in saved in CompletedDate column.
For some reason, I need to get the all sales done in a certain UserSessionID where the CompletedDate must be within the SessionOpenDate and SessionCloseDate. However, if the user has not logged off yet, which means that the value in SessionCloseDate is null, the CompletedDate should be between SessionOpenDate and now.
Here’s my query:
SELECT SUM(s.cost) AS Cost, SUM(s.price) AS Price
FROM Sale AS s
INNER JOIN UserSession AS u
ON s.userID = u.userID
WHERE
(s.CompletedDate >=
( SELECT SessionOpenDate
FROM UserSession
WHERE (UserSessionID = u.UserSessionID)
)
)
AND
(s.CompletedDate <
(
IF EXISTS
(
SELECT SessionCloseDate AS closeTime
FROM UserSession AS UserSessionTemp
WHERE (UserSessionID = u.UserSessionID)
)
BEGIN
SET closeTime = SELECT CURRENT_TIMESTAMP
END
)
)
AND u.UserSessionID IN (1)
However, Sql Server says Incorrect syntax near the keyword 'IF'. and Incorrect syntax near ')'.
Can anyone tell me what went wrong with my IF block?
You can’t use an
IFblock inside aSELECTstatement. Also, I don’t know what you’re really trying to accomplish withSET, sincecloseTimeis not a variable/parameter.You can use
IIFin SQL Server 2012 (syntactical sugar forCASE WHEN <condition> THEN <true_value> ELSE <false_value> END– use this syntax for earlier versions):Honestly, without getting too complicated, here’s what I would do instead:
Or,