想要从SQL Select Query中删除结果

时间:2013-06-06 16:04:39

标签: sql sql-server windows-server-2012

我想从SQL查询中删除结果。

这是查询。

SELECT Name.ID, Name.FULL_NAME, Name.CHAPTER, Subscriptions.BEGIN_DATE, Name.MEMBER_TYPE, Subscriptions.PRODUCT_CODE
FROM   test.dbo.Name Name INNER JOIN test.dbo.Subscriptions Subscriptions ON (Name.ID=Subscriptions.ID) AND (Name.BT_ID=Subscriptions.BT_ID)
WHERE  Name.MEMBER_TYPE='DUPE'
ORDER BY Name.ID

以下是我正在使用的Microsoft版本:

  • Microsoft Windows 7
  • SQL Server Management Studio 2012 11.0.3
  • 操作系统6.1.7601

提前感谢您的支持。

2 个答案:

答案 0 :(得分:3)

看起来您正在通过(ID, BT_ID)对识别行。将其存储在表变量中:

declare @to_delete (id int, bt_id int);
insert  @to_delete
select  n.id
,       n.bt_id
from    Subscriptions s
join    Name n
on      n.id = s.id
        and n.bt_id = s.bt_id
where   n.member_type = 'DUPE'

然后从两个表中删除:

delete  s
from    Subscriptions s
join    @to_delete td
on      td.id = s.id
        and td.bt_id = s.bt_id

delete  n
from    Name n
join    @to_delete td
on      td.id = n.id
        and td.bt_id = n.bt_id

答案 1 :(得分:0)

最后的答案在正确的轨道上,但可以做得更简单

SELECT Name.ID, Name.BT_ID
INTO #dump
FROM Name Name 
INNER JOIN Subscriptions Subscriptions 
   ON (Name.ID=Subscriptions.ID) AND (Name.BT_ID=Subscriptions.BT_ID)
WHERE  Name.MEMBER_TYPE='DUPE'

delete s from subscriptions s join #dump t on t.BT_ID = s.BT_ID and t.ID = s.ID
delete n from from Name n join #dump t on t.BT_ID = n.BT_ID and t.ID = n.ID

没有理由声明临时表,只需使用select在范围内创建临时表,完成后表就会掉落。容易。