简体   繁体   English

在单个CTE上运行多个SQL查询

[英]Running multiple SQL queries on a single CTE

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. SELECT语句将运行,但是我找不到在后续UPDATE语句中使用CTE的方法。 Is there some way to perform the SELECT and UPDATE using a CTE so I don't have to create a temp table? 有什么方法可以使用CTE执行SELECT和UPDATE,所以我不必创建临时表?

Thanks! 谢谢!

I don't get it. 我不明白 Why are you selecting the id s? 为什么选择id 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. 如果要返回受影响的id ,请使用OUTPUT子句。

By Inner Joining the CTE with the table that you want to update you will only update those joined records. 通过将您要更新的表与CTE内部联接,您将仅更新那些联接的记录。

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. 您可以使用update语句的output子句在更新后获取列表。

https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-2017 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. 首先,我只是通过使用CTE吠叫了错误的树。 Thank you for setting me straight! 谢谢你让我直率! Also, sorry to leave you guessing on software; 另外,很抱歉让您猜测软件; I was using SSMS. 我正在使用SSMS。

Using the OUTPUT clause recommended by Joe and Ryan to update a table and also view the affected records worked. 使用Joe和Ryan建议的OUTPUT子句来更新表并查看受影响的工作记录。

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. 我简要地戳了jarlh建议的VIEW机械师。 It looks like a bit more work than OUTPUT for this instance but I'm inspired to learn all about it now. 在这种情况下,它看起来比OUTPUT还要处理更多的工作,但是我很受鼓舞,现在开始学习所有有关它的知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM