Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Administration
 The real effect of FOR UPDATE

Author  Topic 

ozSQLServer
Starting Member

32 Posts

Posted - 2011-12-22 : 18:59:33
Hi,

In an attempt to understand how can I update using CURSORS, I've tried the following code example:

USE [AdventureWorks2]
GO



DROP PROCEDURE HumanResources.UpdateAllEmployeeHireDateInefficiently
GO

CREATE PROCEDURE HumanResources.UpdateAllEmployeeHireDateInefficiently
AS
BEGIN TRY
SET XACT_ABORT ON
DECLARE curemployee CURSOR FOR SELECT TOP 10
EmployeeID FROM HumanResources.Employee FOR UPDATE
OPEN curemployee
FETCH FROM curemployee

WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE HumanResources.Employee
SET HireDate = GETDATE()
WHERE CURRENT OF curemployee
FETCH FROM curemployee -- to avoid the output row, store it into variable
END
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
PRINT 'An error occured, transaction rolled back'
END CATCH
COMMIT;
GO

EXEC HumanResources.UpdateAllEmployeeHireDateInefficiently


The code runs fine whether the "FOR UPDATE" keyword is used or not.

what is the difference between when the "FOR UPDATE" keyword is used and when it isn't?


Cheers,
ozSQL

namman
Constraint Violating Yak Guru

285 Posts

Posted - 2011-12-24 : 00:59:12
what is the difference between when the "FOR UPDATE" keyword is used and when it isn't?


For Update is to indicate which columns can be updated in the cursor. By default (1), all column can be updated

Run the sp with the two below, you will see the different

1 - EmployeeID FROM HumanResources.Employee FOR UPDATE
2 - EmployeeID FROM HumanResources.Employee FOR UPDATE to otherColumnsButNotHireDate

Go to Top of Page
   

- Advertisement -