我想獲取 CTE 查詢的結果并在另一個查詢中使用它。
此簡化示例使用 CTE 查詢來回傳 ID 串列。
with test_cte (id,name) as (
select id, name
from test
)
select id
from test_cte
where name = 'john'
我想使用這個 id 串列來洗掉一些這樣的記錄,但出現語法錯誤:
delete from test
where id in (
with test_cte (id,name) as (
select id, name
from test
)
select id
from test_cte
where name = 'john'
)
有沒有辦法做到這一點?
uj5u.com熱心網友回復:
你的意思是這樣嗎:
;with test_cte(id,name) as
(
select id,name from dbo.test
)
delete test_cte where name='john';
是否要洗掉行并顯示已洗掉的行?
;with test_cte(id,name) as
(
select id,name from dbo.test
)
delete test_cte
output deleted.id, deleted.name
where name='john';
- 示例資料庫<>小提琴
以您的明確示例為例:
delete from test
where id in (
with test_cte (id,name) as (
select id, name
from test
)
select id
from test_cte
where name = 'john'
)
您收到語法錯誤,因為您的語法有錯誤。CTE 必須預先定義,而不是在查詢中的任何隨機或任意點。
;with test_cte (id,name) as (
select id, name
from test
)
delete from test
where id in (
select id
from test_cte
where name = 'john'
)
但與我展示的更簡單的例子相比,這似乎仍然過于復雜。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/370180.html
標籤:sql sql-server 查询语句 公用表表达式
上一篇:如何根據動態標準計算運行最小值?
