0

谁能帮我完成这个任务..

   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  
4

2 回答 2

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

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

于 2012-07-03T14:42:53.433 回答
0

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

 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;
于 2012-07-04T10:42:19.040 回答