I’m trying to select rows one by one in a while loop in SQL Server. And I’m using the only way I know to select the next row using ROW_NUMBER function. But I also have to assign values to t-sql variables in the same SELECT statement thus I’m getting the following error;
A SELECT statement that assigns a value to a variable must not
be combined with data-retrieval operations.
Anyway my code is like this;
WHILE (@i < 5)
BEGIN
SELECT -- This is where the error occurs
@resultId = video.id, -- this is the value assigning i need to do
ROW_NUMBER() OVER (ORDER BY dateAdded DESC) AS ROWID
FROM videoTest.dbo.video
LEFT JOIN videoTest.dbo.aspnet_Users
ON video.userId=aspnet_Users.UserId
WHERE aspnet_Users.UserName=@searchUserName AND ROWID = @i
-- Processing @resultId
SELECT
compilationId
FROM videoTest.dbo.comp
WHERE vidId = @resultId -- i need the id from above
....
....
.....
......
@i = @i + 1
END
I would be much appreciated if you can show me way to select next in an alternative way without getting this error, or a way to solve this error in my current code.
Thanks.
You need to separate out the selection of the data from the retrieval of that data into a variable. You could use e.g. a CTE (Common Table Expression) to set up the data, and then operate on that data. However, on a more basic level : why are you assigning the
idto@resultIdfive times?? You don’t seem to be doing anything with the@resultIdin the meantime…..Could you change your logic to be more set-based ? Instead of a
WHILEconstruct – just select the appropriate values from the CTE:Update: if you need the five
video.idvalues for later processing, try something like this: