2012-10-16 45 views
1

我有一個CTE,它根據ID號將一組人縮減。目前我沒有一個好的方法來測試它。我之前沒有使用CTE和刪除語句,我認爲這是正確的,但我想在確定之後繼續。在刪除聲明中使用CTE SQL Server 2008 r2

我沒有測試這一點,我得到了以下錯誤:

(0 row(s) affected)
Msg 208, Level 16, State 1, Line 35
Invalid object name '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) 
+0

不是downvoter,但什麼是你的問題1上? – LittleBobbyTables

+0

我要編輯該問題,請參閱。 – wootscootinboogie

+0

那麼你可以把所有的特色帶出來,爲什麼你不能測試它? –

回答

2

我覺得你的CTE是錯的 - 你有一個名爲CTE和x那裏面CTE你有一個子查詢也aliassed是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內部的額外子查詢,果然任何好處....