按ID删除多行并检查这些ID是否不在其他表中

时间:2015-10-22 08:17:07

标签: sql-server delete-row

我有一个我要删除的ids列表,但是我必须先检查这些ID是否不在其他表中。如果它们是我想将这些ID插入到按列分隔的另一个列表中。假设@keywordsids的列表。

SELECT Replace(item,'''','') AS KeywordId 
FROM   Splitdelimiterstring(@keywords,',')IF NOT EXISTS 
( 
       SELECT KeywordId 
       FROM   ContentKeyword 
       WHERE  KeywordId = ?? 
       UNION 
       SELECT KeywordId 
       FROM   JobKeyword 
       WHERE  KeywordId = ?? 
       UNION 
       SELECT KeywordId 
       FROM   CategoryGroup 
       WHERE  KeywordId= ?? ) 
BEGIN 
  DELETE 
  FROM   Keywords 
  WHERE  KeywordId =??
END
  ELSE ??

2 个答案:

答案 0 :(得分:1)

您需要做的第一件事是编写一个可以将字符串拆分为表的UDF。这是我的版本。

CREATE  FUNCTION fn_Split(@Text varchar(MAX), @Delimiter varchar(20) = ',')
RETURNS @Strings TABLE
(   
  Position int IDENTITY PRIMARY KEY,
  Value varchar(MAX)  
)
AS
BEGIN

DECLARE @Index int = -1

WHILE (LEN(@Text) > 0)
  BEGIN 
    SET @Index = CHARINDEX(@Delimiter , @Text) 

    IF (@Index = 0) AND (LEN(@Text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@Text)
          BREAK 
      END 

    IF (@Index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@Text, @Index - 1))  
        SET @Text = RIGHT(@Text, (LEN(@Text) - @Index)) 
      END 
    ELSE
      SET @Text = RIGHT(@Text, (LEN(@Text) - @Index))

    END
  RETURN
END

下一步是编写一个select语句,该语句仅从您的字符串中选择不是在您的任何一个表格中ContentKeywordJobKeyword,{{ 1}})。手头有上述功能,这很简单。只需在函数上执行CategoryGroup并检查连接表的ID是否为空:

LEFT JOIN

修改

这是我完整的测试脚本:

select s.Value from dbo.fn_Split('1,2,3,4,5', ',') s
  left outer join ContentKeyword CK on CK.KeywordId = s.Value
  left outer join JobKeyword     JK on JK.KeywordId = s.Value
  left outer join CategoryGroup  JG on JG.KeywordId = s.Value
where 
  (1 = 1)
  and CK.KeywordId is null 
  and JK.KeywordId Is null 
  and JG.KeywordId is null

答案 1 :(得分:1)

declare @temptable as table(
Id int
);
Insert into @temptable values(//ids)

Delete from Keyword
where Id not in (
Select KeywordId from JobKeyword 
where KeywordId in (select Id from @temptable)
union 
Select KeywordId from ContentKeyword
where KeywordId in 
(Select Id from @temptable)
union 
Select KeywordId from CategoryGroup 
where KeywordId in 
(Select Id from @temptable)
)


Select Keyword from Keyword where Id 
in( 
Select Id from @temptable
where Id not in 
(
Select KeywordId from JobKeyword 
where KeywordId in (select Id from @temptable)
union 
Select KeywordId from ContentKeyword
where KeywordId in 
(Select Id from @temptable)
union 
Select KeywordId from CategoryGroup 
where KeywordId in 
(Select Id from @temptable) 
) 
) for xml auto 

怎么样?