为什么这个游标会在每一行中插入相同的值?

Why does this cursor insert the same values into each row?

此游标应该 select 公司成立的年份,然后从当前年份中减去该年份并将结果插入名为年份 运行 的行中。它部分工作,但是它将第一次计算的结果放入每一行,然后移动到第二行并将第二次计算的结果放入每一行。如何将第一个的结果放入第一行,然后将第二个的结果放入第二行,依此类推。

  --Declaring variables for the cursor, I will need to pull out the year the company was founded in 
    --from the table.

    DECLARE @Yearfounded int
    --Now I am going to start work on the cursor

    --Declares my cursor

    DECLARE @YearsCursor CURSOR

    -- sets the cursor to select the column I want

    SET @YearsCursor = CURSOR FOR SELECT  [YEar] From dbo.YearsRunning

    -- Opens the cursor
    OPEN @YearsCursor

    -- selects the next value from years column and puts it into variable

    FETCH NEXT FROM @YearsCursor into @Yearfounded

    -- while there are rows
    WHILE @@FETCH_STATUS = 0

    -- starts the loop
    Begin

    -- declaring variables that are used 
    DECLARE @CurrentYear int = year(getdate())
    DECLARE @YearsRunning int

    Update dbo.YearsRunning SET YearsRunning  =  @CurrentYear - @Yearfounded

    print @YearsRunning




    Fetch Next From @YearsCursor into @Yearfounded

    --UPDATE dbo.YearsRunning SET YearsRunning = @YearsRunning
    -- fetches the next year
    End

    Close @YearsCursor
    Deallocate @YearsCursor 

光标的每一步都会更新 table 中的所有行,因为 UPDATE 语句中没有任何条件。

更新 要逐行更新每一行,您应该修改查询以获取 UPDATE 语句,例如:

Update dbo.YearsRunning 
SET YearsRunning  =  @CurrentYear - @Yearfounded
WHERE id = @Id

id 在这种情况下是您的唯一密钥。但是以这种方式更新是一种不好的做法。您最好使用数据集,但不要使用单独的行。例如:

UPDATE dbo.YearsRunning 
SET YearsRunning = YEAR(GETDATE()) - [YEar]

为什么需要游标?

Update dbo.YearsRunning SET YearsRunning = year(getdate()) - YEar