Select for Update with SQL Server

SELECT FOR UPDATE with SQL Server

Recently I had a deadlock problem because Sql Server locks more then necessary (page). You can't really do anything against it. Now we are catching deadlock exceptions... and I wish I had Oracle instead.

Edit:
We are using snapshot isolation meanwhile, which solves many, but not all of the problems. Unfortunately, to be able to use snapshot isolation it must be allowed by the database server, which may cause unnecessary problems at customers site. Now we are not only catching deadlock exceptions (which still can occur, of course) but also snapshot concurrency problems to repeat transactions from background processes (which cannot be repeated by the user). But this still performs much better than before.

How do I UPDATE from a SELECT in SQL Server?


UPDATE
Table_A
SET
Table_A.col1 = Table_B.col1,
Table_A.col2 = Table_B.col2
FROM
Some_Table AS Table_A
INNER JOIN Other_Table AS Table_B
ON Table_A.id = Table_B.id
WHERE
Table_A.col3 = 'cool'

SQL Server select for update

You can simple do an UPDATE that also reads out the new value into a SQL Server variable:

DECLARE @Output INT

UPDATE dbo.YourTable
SET @Output = YourColumn = YourColumn + 1
WHERE ID = ????

SELECT @Output

Since it's an atomic UPDATE statement, it's safe against concurrency issues (since only one connection can get an update locks at any one given time). A potential second session that wants to get the incremented value at the same time will have to wait until the first one completes, thus getting the next value from the table.

SQL Server 2008: SELECT FOR UPDATE

You need to use one of the so-called table hints:

The update lock prevents other processes from attempting to update or delete the rows in question - but it does not prevent read access:

    SELECT TOP (20) * 
FROM [TMA_NOT_TO_ENTITY_QUEUE] WITH (UPDLOCK)
WHERE [TMA_NOT_TO_ENTITY_QUEUE].[STATE_ID] = 2
ORDER BY TMA_NOT_TO_ENTITY_QUEUE.ID

There's also an exclusive lock, but basically, the update lock should be enough. Once you've selected your rows with an update lock, those rows are "protected" against updates and writes until your transaction ends.

SQL UPDATE SELECT with WHERE

You need to do a check on ClassName as well:

update b1
set b1.defaultguid =
(
select b2.defaultguid
from cSC_BusinessUnit b2
where b2.BusinessUnitGUID = 5
AND b2.ClassName = b1.ClassName
)
from cSC_BusinessUnit b1
where b1.BusinessUnitGUID = 7

How to select and update in one query?

Resolve this!

DECLARE @id int;
SET @id = (select top(1) id from [table] where [x] = 0 order by id desc);

select * from [table] where id = @id;
update [table] set [x] = 20 where id = @id;

:D

SQL - on which context do SELECT...FOR UPDATE and UPDATE work?

In this case transactions cannot run simultaneously - first transaction, which would be run, will lock record with id = 1.

They do not have two their own states - only one transaction will work and it should see own changes

sql how to select and update at the same time

You can use OUTPUT clause:

UPDATE dbo.tableName 
SET processed = 2 --or whatever you want..
OUTPUT inserted.*
WHERE processed = @processed

From MSDN (Link above):

Returns information from, or expressions based on, each row affected
by an INSERT, UPDATE, DELETE, or MERGE statement. These results can be
returned to the processing application

Is there a way to SELECT and UPDATE rows at the same time?

Consider looking at the OUTPUT clause:

USE AdventureWorks2012;  
GO

DECLARE @MyTableVar table(
EmpID int NOT NULL,
OldVacationHours int,
NewVacationHours int,
ModifiedDate datetime);

UPDATE TOP (10) HumanResources.Employee
SET VacationHours = VacationHours * 1.25,
ModifiedDate = GETDATE()
OUTPUT inserted.BusinessEntityID,
deleted.VacationHours,
inserted.VacationHours,
inserted.ModifiedDate
INTO @MyTableVar;

--Display the result set of the table variable.
SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate
FROM @MyTableVar;
GO
--Display the result set of the table.
SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate
FROM HumanResources.Employee;
GO

When to use SELECT ... FOR UPDATE?

The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE.

However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE explicitly.


To solve this problem, Thread 1 should SELECT id FROM rooms FOR UPDATE, thereby preventing Thread 2 from deleting from rooms until Thread 1 is done. Is that correct?

This depends on the concurrency control your database system is using.

  • MyISAM in MySQL (and several other old systems) does lock the whole table for the duration of a query.

  • In SQL Server, SELECT queries place shared locks on the records / pages / tables they have examined, while DML queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT or DELETE query will lock until another session commits.

  • In databases which use MVCC (like Oracle, PostgreSQL, MySQL with InnoDB), a DML query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE would come handy: it would lock either SELECT or the DELETE query until another session commits, just as SQL Server does.

When should one use REPEATABLE_READ transaction isolation versus READ_COMMITTED with SELECT ... FOR UPDATE?

Generally, REPEATABLE READ does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)

  • In Oracle and earlier PostgreSQL versions, REPEATABLE READ is actually a synonym for SERIALIZABLE. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1 query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE

  • In InnoDB, REPEATABLE READ and SERIALIZABLE are different things: readers in SERIALIZABLE mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML on them. So you don't need a SELECT FOR UPDATE in serializable mode, but do need them in REPEATABLE READ or READ COMMITED.

Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC or otherwise).

When I say "you don't need SELECT FOR UPDATE" I really should have added "because of side effects of certain database engine implementation".



Related Topics



Leave a reply



Submit