Sql server 2008 r2 在SQL Server 2008 r2的Delete语句中使用CTE

Sql server 2008 r2 在SQL Server 2008 r2的Delete语句中使用CTE,sql-server-2008-r2,common-table-expression,Sql Server 2008 R2,Common Table Expression,我有一个CTE,它根据一组人的身份证号码对他们进行筛选。我现在没有一个好的方法来测试这个。我以前没有将CTE与delete语句结合使用,我认为这是正确的,但我想在确定之后继续 我做了测试,得到了以下错误: (受影响的0行) 味精208,第16级,状态1,第35行 无效的对象名称“x” 我做错了什么 --this CTE pares down the number of people that I need for my final result set ;with x as (select di

我有一个CTE,它根据一组人的身份证号码对他们进行筛选。我现在没有一个好的方法来测试这个。我以前没有将CTE与delete语句结合使用,我认为这是正确的,但我想在确定之后继续

我做了测试,得到了以下错误:

(受影响的0行)
味精208,第16级,状态1,第35行
无效的对象名称“x”

我做错了什么

--this CTE pares down the number of people that I need for my final result set
;with x as (select distinct patid from
(
select distinct patid
    from clm_extract
    where (diag1 like '952%' or diag1 like '806%') and drg =444

union
select distinct patid
    from clm_extract
    where (diag2  like '952%' or diag2 like '806%') and drg =444

union
select distinct patid
    from clm_extract
    where (diag3  like '952%' or diag3  like '806%') and drg =444
union
select distinct patid
    from clm_extract
    where (diag4  like '952%' or diag4  like '806%') and drg =444
union
select distinct patid
    from clm_extract
    where (diag5  like '952%' or diag5  like '806%') and drg =444
) x

)
--this is a query to show me the list of people that I need to delete from this table because they do not match the criteria
select distinct x.patid
    from x
    inner join clm_extract as c on c.patid = x.patid
    where x.patid !=1755614657 (1 person did match)

--this is my attempt at using a CTE with said query to remove the IDs that I don't need from my table

delete from clm_extract
where patid in(select distinct x.patid
    from x
    inner join clm_extract as c on c.patid = x.patid
    where x.patid !=1755614657)

我认为您的CTE是错误的-您有一个名为
x
的CTE,在该CTE中您有一个子选择,它的别名也是
x
-这会造成混淆

为什么不干脆:

;with x as 
(
    select distinct patid
    from clm_extract
    where (diag1 like '952%' or diag1 like '806%') and drg =444

    union

    select distinct patid
    from clm_extract
    where (diag2  like '952%' or diag2 like '806%') and drg =444

    ......     
)
select 
    distinct x.patid
from x
inner join clm_extract as c on c.patid = x.patid
where x.patid !=1755614657 (1 person did match)

我不认为在CTE中有额外的子查询有任何必要,也没有任何好处,真的……

不是downvoter,但你的问题是什么?我将编辑这个问题,请看。好吧,你可以从那里开始所有的区别,为什么你不能测试它?我不是在一个可以轻松完成的终端。我已经移动、测试和删除了,错误信息在问题中。