如何删除主表中与临时表中的ID匹配的行?

时间:2014-12-13 17:42:39

标签: sql .net sql-server tsql

下面是我的SQL代码。在删除部分中,对象" tblDeletes"我在WITH语句中声明给了我无效的对象名称,可能是什么错误?谢谢。

    USE [NEDB_beta]
GO
/****** Object:  StoredProcedure [dbo].[cms_cpAdminDeleteContentItemById]    Script Date: 12/13/2014 12:11:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[cms_cpAdminDeleteContentItemById] 
@ID int
AS
BEGIN
WITH    tblDeletes AS 
        (
        SELECT  *
        FROM    [NEDB_beta].[dbo].[cms_tblContent]
        WHERE   ID = @ID -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  c.*
        FROM    [NEDB_beta].[dbo].[cms_tblContent] as c
        JOIN    tblDeletes
        ON      c.intParentIdDraft = tblDeletes.ID
        )
SELECT  *
FROM    tblDeletes

DELETE FROM [NEDB_beta].[dbo].[cms_tblContent] 
WHERE ID IN 
    (SELECT ID 
     FROM tblDeletes);

END

2 个答案:

答案 0 :(得分:2)

因为您正在使用CTE,并且仅为一个查询定义了CTE。但在这里你使用相同的CTE。 CTE范围仅适用于一个语句,您不能使用它两次。

删除select语句,在CTE创建之后,我认为这不是必需的,因为你的主要动机是删除记录。

但是如果你想使用SELECT语句,那么重复CTE创建步骤或代替CTE使用Temp表。

ALTER PROCEDURE [dbo].[cms_cpAdminDeleteContentItemById] 
@ID int
AS
BEGIN
WITH    tblDeletes AS 
        (
        SELECT  *
        FROM    [NEDB_beta].[dbo].[cms_tblContent]
        WHERE   ID = @ID -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  c.*
        FROM    [NEDB_beta].[dbo].[cms_tblContent] as c
        JOIN    tblDeletes
        ON      c.intParentIdDraft = tblDeletes.ID
        )

DELETE FROM [NEDB_beta].[dbo].[cms_tblContent] 
WHERE ID IN 
    (SELECT ID 
     FROM tblDeletes);

END

答案 1 :(得分:0)

您可以在其后的语句中使用Common Table Expression。您已将其用于SELECT。之后它不再“存在”。