【问题标题】:Using a CTE in a Delete Statement SQL Server 2008 r2在删除语句 SQL Server 2008 r2 中使用 CTE
【发布时间】:2012-10-16 17:19:21
【问题描述】:

我有一个 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)

【问题讨论】:

  • 不是反对者,但你的问题是什么?
  • 我要编辑问题,请看。
  • 好吧,你可以把所有不同的东西都拿出来作为初学者,你为什么不能测试一下呢?
  • 我不在一个可以轻松完成的终端。我已经搬家了,经过测试,并且错误消息在问题中。

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


【解决方案1】:

我认为您的 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 中添加额外的子查询没有任何必要或任何好处,真的....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多