#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Posts
    69
    Rep Power
    10

    SQL server 2012 returns different result than SQL server 2008


    Hi,
    I have a piece of script using cursor to sequence rows in a table. For example, the table looks like this,
    SSN, Kid_SSN, Kid_DOB, Seq# to list every person with 1 or more kids. I want to update Seq# to label each kid as 1,2,3... based on Date Of Birth.
    I used cursor for update to get it done successfully in SQL server 2008. My current trouble is that this same script wouldn't run as expected in sql server 2012. The problem is in SQL 2012 cursor fetch NEXT more than 1 row at a time. So question is where can I set the cursor fetch size? I searched around but came up no good answer.
    Anyone here can shed some light? thanks.

    Scrip looks like this:

    DECLARE @SocialSecurity varchar(9), @PersonID int, @Dep_SSN varchar(9), @LastName varchar(20),
    @FirstName varchar(20), @BirthDate datetime, @Number int

    DECLARE @ssn varchar(9) = '000000000'
    DECLARE @Mem int = 1
    DECLARE cur cursor
    FOR SELECT * FROM kids
    FOR UPDATE OF Number;

    OPEN cur;

    FETCH NEXT FROM cur INTO @SocialSecurity, @PersonID, @Dep_SSN, @LastName, @FirstName, @BirthDate, @Number;

    WHILE @@FETCH_STATUS = 0
    BEGIN

    IF @SocialSecurity = @ssn
    BEGIN

    UPDATE kids
    SET Number = @Mem+1
    WHERE CURRENT OF cur
    SET @Mem = @Mem+1
    END;
    ELSE
    BEGIN
    SET @ssn = @SocialSecurity
    SET @Mem = 1
    END;
    FETCH NEXT FROM cur INTO @SocialSecurity, @PersonID, @Dep_SSN, @LastName, @FirstName, @BirthDate, @Number;
    END;
    CLOSE cur;
    DEALLOCATE cur;
    Last edited by sqgs; October 23rd, 2012 at 03:09 PM.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Jan 2003
    Location
    Paris Uppland
    Posts
    2,375
    Rep Power
    391
    The problem is that you don't have an order by clause in the cursor declaration. Anyhow, you don't need a cursor at all.

    Code:
    update kids
       set Number = row_number() over (partition by ssn order by kid_dob desc)
    Last edited by swampBoogie; October 24th, 2012 at 06:08 AM.

IMN logo majestic logo threadwatch logo seochat tools logo