SELECT() next row in value assigning statement?
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 id
to @resultId
five times?? You don't seem to be doing anything with the @resultId
in the meantime.....
Could you change your logic to be more set-based ? Instead of a WHILE
construct - just select the appropriate values from the CTE:
;WITH VideoData AS
(
SELECT
video.id,
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
)
SELECT id, ROWID
FROM VideoData
WHERE ROWID <= 5
Update: if you need the five video.id
values for later processing, try something like this:
DECLARE @VideoIDs TABLE (VideoID INT)
;WITH VideoData AS
(
... (same as before)
)
INSERT INTO @VideoIDs(VideoID)
SELECT id
FROM VideoData
WHERE ROWID <= 5
-- use your values in the table variable here.....
I see that you need video.id. Why not just order by dateAdded, and store it in a cursor:
SELECT
INTO CURSOR @SomeCursor
video.id
FROM videoTest.dbo.video
LEFT JOIN videoTest.dbo.aspnet_Users
ON video.userId=aspnet_Users.UserId
WHERE aspnet_Users.UserName=@searchUserName
ORDER BY dateAdded DESC
and then iterate @SomeCursor?
精彩评论