Reputation: 23
TOP
command? SELECT
statement which does not support SQL variables?My code:
DECLARE @cnt INTEGER = 0;
Declare @cnt_total INT;
SET @cnt_total = 5
WHILE (@cnt < @cnt_total)
BEGIN
SET @cnt = @cnt + 1;
SELECT TOP @cnt *
FROM FOCUSCDR.PATIENTDXHISTORY
END;
Error:
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near '@cnt'.
While above works when used.
SELECT TOP 1 *
FROM FOCUSCDR.PATIENTDXHISTORY
Upvotes: 1
Views: 83
Reputation: 4039
Because the syntax requires parentheses:
DECLARE @cnt INTEGER = 0;
Declare @cnt_total int ;
Set @cnt_total = 5
WHILE (@cnt < @cnt_total)
BEGIN
SET @cnt = @cnt + 1;
Select top (@cnt) * from FOCUSCDR.PATIENTDXHISTORY
END;
Edit:
As mentioned in the comment by @Tim Biegeleisen, you should be using ORDER BY, otherwise it makes no sense using TOP since the order will not be guaranteed and you might get non consistent results. Check out this article for more info on it.
Upvotes: 3