删除重复行的存储过程

时间:2016-10-21 16:51:33

标签: sql-server stored-procedures

我需要帮助来解决我的问题:

create procedure dbo.spDelDdup
    (@field1 nvarchar(50)= null,
     @field2 varchar(50),
     @tblName varchar(50))
as
BEGIN
    WITH CTE (@field1, @field2, Duplicate_Record_Count) AS
    (
        SELECT 
            @field1, @field2,
            ROW_NUMBER() OVER(PARTITION BY @field1, @field2 ORDER BY @field1) AS Duplicate_Record_Count
        FROM 
            @tblName
    )
    DELETE FROM CTE
    WHERE Duplicate_Record_Count > 1
END

我收到错误:

  

Msg 102,Level 15,State 1,Procedure spDelDdup,第91行   ' @ field1'。

附近的语法不正确

很高兴解决我的问题

1 个答案:

答案 0 :(得分:1)

您需要使用Dynamic SQL,如下所示:

您还将@field1声明为可选参数,您需要对其进行管理,但这有点奇怪。但如果这正是您想要的,请发表评论,以便我根据它更新我的答案。

create procedure dbo.spDelDdup
(@field1 nvarchar(50)= null,
@field2 varchar(50),
@tblName varchar(50))
as
BEGIN
Declare @q AS Nvarchar(max)
Set @q = N'WITH CTE ('+@field1+', '+@field2+', Duplicate_Record_Count)
AS
(
    SELECT '+@field1+','+@field2+',
    ROW_NUMBER() OVER(PARTITION BY '+@field1+','+@field2+' ORDER BY '+@field1+') AS Duplicate_Record_Count
    FROM '+@tblName+'
)
DELETE
FROM CTE
WHERE Duplicate_Record_Count > 1'

EXEC(@q);

END

您也可以使用sp_executesql