Search code examples
sqlsql-serverdatabasecursor

Simple column update using CURSOR


I created a table and added few rows to it. Here is the script for that.

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON 
GO

CREATE TABLE [dbo].[xEmployee]
(
    [EmpID] [int] NOT NULL,
    [EmpName] [varchar](50) NOT NULL,
    [Salary] [int] NOT NULL,
    [Address] [varchar](200) NOT NULL,
    [YearlySalary] [int] NULL,

    PRIMARY KEY CLUSTERED ([EmpID] ASC)
) ON [PRIMARY]
GO

INSERT INTO [dbo].[xEmployee] ([EmpID], [EmpName], [Salary], [Address], [YearlySalary]) 
VALUES (1, N'Mohan', 12000, N'Noida', NULL),
       (2, N'Pavan', 25000, N'Delhi', NULL)
GO

As you can see, I have a Salary column and its data already present. I added one more column named YearlySalary. This is currently null.

I need to update this YearlySalary column using a cursor. So for 1st and 2nd rows it should be YearlySalary = Salary * 12.

I am trying to use a cursor as shown below. But something is missing or is just not right. Can someone please let me know where I am going wrong?

SET NOCOUNT ON
DECLARE @salary int
DECLARE @id int
DECLARE @yearlySalary int

DECLARE tempCursor CURSOR STATIC FOR
     SELECT EmpID,Salary, YearlySalary 
     FROM dbo.xEmployee 

OPEN tempCursor

IF @@CURSOR_ROWS > 0
BEGIN 
      FETCH NEXT FROM tempCursor INTO @salary

      WHILE @@FETCH_STATUS = 0
      BEGIN
          @yearlySalary = @salary * 12

          INSERT INTO dbo.xEmployee (EmpId, Salary,YearlySalary) 
          VALUES (@id, @salary, @yearlySalary)
      END 
END

CLOSE tempCursor
DEALLOCATE tempCursor
SET NOCOUNT OFF

Solution

  • I should be more patient in doing things on my own. I just wanted to try out cursor for a small simple example so that I can use it for tougher ones later. Here is a way I was able to get it working. Thanks guys.

    SET NOCOUNT ON
    DECLARE @salary int
    DECLARE @Id int
    
    DECLARE tempCursor CURSOR STATIC FOR 
         SELECT EmpId, Salary 
         FROM dbo.xEmployee 
    
    OPEN tempCursor
    
    IF @@CURSOR_ROWS > 0
    BEGIN 
       FETCH NEXT FROM tempCursor INTO @Id, @salary
    
       WHILE @@FETCH_STATUS = 0  
       BEGIN
          print @salary
    
          UPDATE dbo.xEmployee  
          SET YearlySalary = (@salary * 12) 
          WHERE EmpID = @Id;
    
          FETCH NEXT FROM tempCursor INTO @Id, @salary
       END 
    END
    
    CLOSE tempCursor
    DEALLOCATE tempCursor
    SET NOCOUNT OFF