在删除语句SQL Server 2008 r2中使用CTE

时间:2012-10-16 17:19:21

标签: sql-server-2008-r2 common-table-expression

我有一个CTE,根据他们的身份证号码削减了一组人。我目前没有好的方法来测试这个。我之前没有将CTE与删除声明结合使用,我认为这是正确的,但我想在我确定之后再继续。

我测试了这个,我收到了以下错误:

  

(0行(s)受影响)
  Msg 208,Level 16,State 1,Line 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)

1 个答案:

答案 0 :(得分:2)

我认为你的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中有额外的子查询没有任何需要也没有任何好处,真的......