Row_number函数和变量

时间:2014-10-10 08:31:14

标签: sql sql-server tsql row-number

我在查询中使用变量时将ROW_NUMBER置于正确的位置时遇到问题。

我想通过检查从第一个记录到最后一个记录的每个记录来创建查找功能。我使用ROW_NUMBER()函数做错了。有什么提示吗?

/* DECLARATION */
...
/* LOOKUP */
SET @MAXID = (SELECT COUNT(ContractNr) FROM SenoOud.dbo.Financieel)
SET @COUNTER = 1
WHILE @COUNTER < @MAXID
    BEGIN
        SELECT  @ROWNUM = ROW_NUMBER() OVER (ORDER BY ContractNr) AS 'CNUM',
                @IGAS = [Factuur CO/LPG], 
                @IBRAND = [Factuur Brand], 
                @IOVERIG = [Factuur Overig],
        FROM SenOoud.dbo.Financieel
        WHERE @ROWNUM = @COUNTER
/* INSERTION */
...

2 个答案:

答案 0 :(得分:1)

SELECT @IGAS = [Factuur CO/LPG],
       @IBRAND = [Factuur Brand],
       @IOVERIG = [Factuur Overig]
FROM   (SELECT Row_number()
                 OVER (
                   ORDER BY ContractNr) AS ROWNUM,
               [Factuur CO/LPG],
               [Factuur Brand],
               [Factuur Overig]
        FROM   SenOoud.dbo.Financieel) A
WHERE  ROWNUM = @COUNTER

如果仍然出现错误,请尝试使用示例数据进行同样的操作

CREATE TABLE #temp
  (
     col1 VARCHAR(50),
     col2 VARCHAR(50),
     col3 VARCHAR(50)
  )

SELECT *
FROM   #temp

INSERT INTO #temp
VALUES      ('1','A319','zvxfsdg'),
            ('2','efg','ddfgdfg'),
            ('3','xdfg','ddfgxfgdfg')

SELECT col1,
       col2,
       col3
FROM   (SELECT Row_number()
                 OVER (
                   ORDER BY col1) AS ROWNUM,
               col1,
               col2,
               col3
        FROM   #temp) A
WHERE  ROWNUM = 1 

答案 1 :(得分:1)

我认为这种方法效果最好

SELECT Row_number()
         OVER (
           ORDER BY ContractNr) AS RNUM,
       [Factuur CO/LPG],
       [Factuur Brand],
       [Factuur Overig]
INTO   #TEMP
FROM   SenOoud.dbo.Financieel


SET @MAXID = @@ROWCOUNT
SET @COUNTER = 1
WHILE @COUNTER < @MAXID
  BEGIN
      SELECT top 1 @ROWNUM =RNUM,
             @IGAS = [Factuur CO/LPG],
             @IBRAND = [Factuur Brand],
             @IOVERIG = [Factuur Overig]
      FROM   #TEMP
      WHERE  RNUM = @COUNTER

      SET @COUNTER=@COUNTER + 1
END 

我已添加前1名以防万一