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

时间:2017-11-07 11:34:34

标签: sql-server cursor

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

  --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 

2 个答案:

答案 0 :(得分:1)

为什么需要光标?

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

答案 1 :(得分:0)

光标的每一步都会更新表格中的所有行,因为您的UPDATE声明中没有任何条件。

<强> UPD。 要逐个更新每一行,您应修改查询以获取UPDATE语句,如:

Update dbo.YearsRunning 
SET YearsRunning  =  @CurrentYear - @Yearfounded
WHERE id = @Id
在这种情况下,

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

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