使用游标更新记录循环数据库

时间:2012-07-03 08:59:46

标签: sql sql-server

任何人都可以帮我完成这项任务..

   FirstName  LastName  EmpNumber  EffectiveFrom   EffectiveTo    JobTitle
      john     A        EMP01      2004-05-01      2005-09-01     credit officer
      NULL     NULL     NULL       2005-09-01      2006-30-01     chief credit officer
      NULL     NULL     NULL       2006-30-01      2006-30-09
      george   B        EMP02      
      david    C        EMP03
      NULL     NULL     NULL
      NULL     NULL     NULL

我有这样的表,想用光标更新它,看起来像这样 我没有把所有数据写成一些记录

 FirstName  LastName  EmpNumber   EffectiveFrom   EffectiveTo    JobTitle
     john      A       EMP01 
     john      A       EMP01 
     john      A       EMP01 
     george    B       EMP02 
     david     C       EMP03 
     david     C       EMP03 
     david     C       EMP03  

2 个答案:

答案 0 :(得分:0)

创建变量以保存找到的最后一个非空值:@FirstNameNN, @LastNameNN, @EmpNumberNN.

创建游标并获取每行,将其数据保存到变量(@FirstName, @LastName, @EmpNumber, @EffectiveFrom, @EffectiveTo, @JobTitle)。

在每个游标迭代中,执行以下操作:

IF @FirstName IS NOT NULL
BEGIN
    SET @FirstNameNN = @FirstName
    SET @LastNameNN = @LastName
    SET @EmpNumberNN = @EmpNumber 
END
ELSE
BEGIN
    UPDATE Employees
      SET FirstName = @FirstNameNN,
          LastName = @LastNameNN,
          EmpNumber = @EmpNumberNN
    WHERE EffectiveFrom = @EffectiveFrom AND
          EffectiveTo = @EffectiveTo AND
          JobTitle = @JobTitle
END

当然,如果有两行,最后三列相等,则此代码将失败。

答案 1 :(得分:0)

我也用光标制作它,只是复制了@daniloquio代码中的语句。

 DECLARE @NAME  NVARCHAR(500), @LastName NVARCHAR(500), @EmpN NVARCHAR(500), @TN NVARCHAR(500), @TLN NVARCHAR(500), @TEN NVARCHAR(500),
                @EffectiveFrom DATETIME,@EffectiveTo DATETIME,@JobTitle NVARCHAR(500)

DECLARE temp CURSOR FOR
    SELECT  Name, [Last Name], [Employee Number], [Effective From], [Effective To], [Job Title]
    FROM dbo.Positions$

    OPEN temp       

FETCH NEXT FROM temp INTO @Name, @LastName, @EmpN, @EffectiveFrom, @EffectiveTo, @JobTitle

WHILE @@FETCH_STATUS=0
BEGIN
    SELECT @Name, @LastName, @EmpN

    IF @NAME IS NOT NULL
    BEGIN
        SELECT @TN=@NAME, @TLN=@LastName, @TEN=@EmpN
    END
    ELSE
     BEGIN
        UPDATE dbo.Positions$
        SET Name=@TN, 
                [Last Name]=@TLN, 
                [Employee Number]=@TEN 
        WHERE [Effective From] = @EffectiveFrom AND
          [Effective To] = @EffectiveTo AND
          [Job Title] = @JobTitle
     END


    FETCH NEXT FROM temp INTO @Name, @LastName, @EmpN, @EffectiveFrom, @EffectiveTo, @JobTitle
END
CLOSE temp;
DEALLOCATE temp;