Use case: A database table tracks cars on a lot. Each car must be inspected every three months. When I pull a list of cars to inspect, I also want to update their [Status] to reflect that. This can be done by using a temp table, but a common table expression would execute faster and make more sense if it could be used this way.
Attempted solution:
WITH CTE AS (
SELECT ID
FROM [dbo].[CarInventory]
WHERE <car requires inspection> )
SELECT ID
FROM CTE;
UPDATE [dbo].[CarInventory]
SET Status = 'Queued for inspection'
WHERE ID IN (SELECT ID FROM CTE);
The SELECT statement would run but I cannot find a way to use the CTE in the subsequent UPDATE statement. Is there some way to perform the SELECT and UPDATE using a CTE so I don't have to create a temp table?
Thanks!
I don't get it. Why are you selecting the id
s? Just do:
UPDATE ci
SET Status = 'Queued for inspection'
FROM [dbo].[CarInventory] ci;
WHERE <car requires inspection> ;
If you want to return the id
s that are affected, use an OUTPUT
clause.
By Inner Joining the CTE with the table that you want to update you will only update those joined records.
WITH CTE AS
(
SELECT ID
FROM [dbo].[CarInventory]
WHERE <car requires inspection>
)
UPDATE [dbo].[CarInventory]
SET Status = 'Queued for inspection'
OUTPut CTE.*
FROM [dbo].[CarInventory]
INNER JOIN CTE ON [dbo].[CarInventory].ID = cte.ID
You can use the output clause of the update statement to get the list after the update.
https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-2017
I was simply barking up the wrong tree by using CTE in the first place. Thank you for setting me straight! Also, sorry to leave you guessing on software; I was using SSMS.
Using the OUTPUT clause recommended by Joe and Ryan to update a table and also view the affected records worked.
UPDATE [dbo].[CarInventory]
SET Status = 'Queued for inspection'
OUTPUT Deleted.ID
WHERE <car requires inspection>
I briefly poked at the VIEW mechanic that jarlh suggested. It looks like a bit more work than OUTPUT for this instance but I'm inspired to learn all about it now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.