我有桌子,它有以下列:
pkID int
Title varchar(255)
FromEmail varchar(500)
ToEmail varchar(500)
CCEmail varchar(500)
BCCEmail varchar(500)
Subject varchar(500)
EmailBody ntext
EmailFields varchar(5000)
我的表格 4行数据相同值,如下所示
pkID 44
Title 'Notification'
FromEmail NULL
ToEmail NULL
CCEmail NULL
BCCEmail NULL
Subject 'Send Email for Notification'
EmailBody NULL
EmailFields NULL
我的表名是EmailTemplates
如果我尝试此查询:
;WITH cte
(
SELECT
*, ROW_NUMBER() OVER (ORDER BY pkID) RN
FROM EmailTemplates
WHERE pkID = 44
)
DELETE FROM cte
WHERE RN > 1
我收到此错误:
Msg 156,Level 15,State 1,Line 3
关键字附近的语法不正确'选择'。Msg 102,Level 15,State 1,Line 6
')'附近的语法不正确。
我想删除pkID 等于44 它会删除4行,那么我怎么能删除3行pkID等于44 ?
感谢。
答案 0 :(得分:3)
将CTE
与row_number
一起使用以删除重复项
;with cte as
(
select *,row_number() over(order by pkID) RN
FROM yourtable
where pkID = 44
)
delete from cte where RN>1
注意:在order by
中,您可以提及order
要删除的duplicates
答案 1 :(得分:1)
您可以使用CTE和ROW_NUMBER
。它允许轻松更改以查看哪些行已删除(或更新),因此只需将DELETE FROM CTE...
更改为SELECT * FROM CTE
:
WITH CTE AS(
SELECT e.*,
RN = ROW_NUMBER() OVER (PARTITION BY pkID ORDER BY pkID)
FROM dbo.EmailTemplates e
WHERE pkID = @pkID -- if you want to delete only a specific ID
)
DELETE FROM CTE WHERE RN > 1
如果您删除WHERE pkID = @pkID
,则每个pkID
始终保留一行,您将删除所有重复项。因此,如果您想将逻辑更改为更有意义的内容,则需要将ORDER BY pkID
更改为不同的内容,目前它是任意的。
如果您想考虑多个栏目,只需将PARTITION BY pkID
更改为(f.e。)PARTITION BY pkID, Title
。