1

我有一个 CTE,它根据他们的 ID 号减少一组人。我目前没有很好的方法来测试这个。我之前没有将 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)
4

1 回答 1

2

我认为你的 CTE 是错误的 - 你有一个 CTE 被调用x,并且在那个 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 中包含额外的子查询没有任何必要或任何好处,真的....

于 2012-10-16T17:28:29.373 回答