简体   繁体   中英

Row_number function and variables

I have a problem placing the ROW_NUMBER onto the right spot while I am using variables in my query.

I want to create a lookup function by checking every record from the first till the last record. There's something I'm not doing right with the ROW_NUMBER() function. Any tips?

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

If you still get error try this same thing i have done with sample data

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 

I think this approach will work best

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 

I have added top 1 just in case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM