SQL Server : does an CTE update work like a transaction?

Viewed 812

I use a query like this to update some columns of a table:

WITH MyTable AS
(
    SELECT TOP 1 
        *, 
        ROW_NUMBER() OVER (ORDER BY T.dtDate ASC) AS RowNum
    FROM 
        important.Table T
    WHERE 
        bWorking = 1
)
UPDATE MyTable
SET iIDfkToOtherTable = 6
WHERE RowNum = 1

There are two queries in this statement (SELECT and UPDATE), so I'm not sure if another user will be able to change the "important.Table" values while I am between the SELECT and the UPDATE. Can someone give me a clue? Thanks!

2 Answers

Don't think of it as two queries. That's procedural thinking. SQL Server is set based, and in this case you are defining an end state "This set of data will have this transformation applied".

As a single definition it will always be atomic.

Related