SELECT()值赋值语句的下一行?

时间:2011-07-28 20:22:06

标签: sql sql-server tsql stored-procedures select

我正在尝试在SQL Server中的while循环中逐个选择行。我正在使用我知道的唯一方法使用ROW_NUMBER函数选择下一行。但我还必须在同一SELECT语句中为t-sql变量赋值,因此我收到以下错误;

  

不能为变量赋值的SELECT语句   与数据检索操作相结合。

无论如何,我的代码是这样的;

   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

如果你能告诉我以另一种方式选择next而不会出现此错误,或者在我当前的代码中解决此错误的方法,我将不胜感激。 感谢。

2 个答案:

答案 0 :(得分:4)

您需要将数据的选择与将数据检索分离为变量。你可以用例如CTE(公用表表达式)用于设置数据,然后对该数据进行操作。但是,在更基础的层面上:为什么要将id分配给@resultId五次?在此期间,您似乎没有对@resultId做任何事情......

您可以将逻辑更改为基于集合吗?而不是WHILE构造 - 只需从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

更新:如果您需要五个video.id值供以后处理,请尝试以下操作:

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.....

答案 1 :(得分:0)

我看到你需要video.id。为什么不按dateAdded排序,并将其存储在游标中:

   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

然后迭代@SomeCursor?