选择第n行并将其分配给变量

时间:2015-01-20 13:57:48

标签: sql sql-server

我想选择第n行并将其分配给变量。到目前为止我有这个:

  DECLARE @LEVEL INT;   
  DECLARE @COUNT INT = 14;
  DECLARE @A INT = 1;       

    SET @LEVEL = (SELECT * FROM 
    (SELECT ROW_NUMBER() OVER (ORDER BY Q_Total) AS rownumber, Q_Response 
    FROM #Qtemp) AS name WHERE rownumber = @COUNT - @A);

选择查询似乎有效,但我收到此错误:

Msg 116,Level 16,State 1,Line 176 当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式。

我正在做的事情还是有另外一种方法可以做到这一点? 谢谢!

1 个答案:

答案 0 :(得分:2)

您的代码有错误。将select result赋值给value时,它必须在结果集中包含一列。改为

DECLARE @LEVEL INT;   
  DECLARE @COUNT INT = 14;
  DECLARE @A INT = 1;       

    SET @LEVEL = (SELECT  Q_Response FROM 
    (SELECT ROW_NUMBER() OVER (ORDER BY Q_Total) AS rownumber, Q_Response 
    FROM #Qtemp) AS name WHERE rownumber = @COUNT - @A);

如果您使用SQL 2012,则可能会简化

DECLARE @LEVEL INT;   
DECLARE @COUNT INT = 14;
DECLARE @A INT = 1;       

SELECT @LEVEL = Q_Response FROM  #Qtemp
ORDER BY Q_Total
OFFSET @COUNT - @A ROWS FETCH FIRST 1 ROW ONLY