如何使用IN子句删除记录

时间:2017-03-10 03:04:35

标签: sql-server stored-procedures

我有一个存储过程,它插入记录但是使用逗号分隔的字符串并解析它并添加单个记录

     Create PROCEDURE [dbo].[Save_List_PMIDS]
     @MemberID INT=  88888,
     @PMIDList VARCHAR(MAX)= '12345,56789,67432'

     AS
     BEGIN

    SELECT Split.a.value('.', 'VARCHAR(100)') AS PMID
    INTO   #pmids
    FROM   ( SELECT    CAST ('<M>' + REPLACE(@PMIDList, ',', '</M><M>') + '</M>' AS XML) AS String
    ) AS A
    CROSS APPLY String.nodes('/M') AS Split ( a )   

     --DELETE FROM [dbo].[Publication.Person.Include]
      --WHERE (MemberID = @MemberID) AND PMID IN (@PMIDList);

INSERT INTO [dbo].[Publication.Person.Include]
    ( PersonID, PMID, MemberID )
    SELECT  @MemberID, PMID, @MemberID
    FROM    #pmids

    DROP TABLE #pmids

我的问题在于删除语句。如何将PMIDList字符串转换为要在IN列表中使用的数字,以便我不添加重复项?

所以它看起来像

  DELETE FROM [dbo].[Publication.Person.Include]
  WHERE (MemberID = @MemberID) AND PMID IN (12345,56789,67432);

提前致谢

1 个答案:

答案 0 :(得分:2)

为什么要使用字符串?您的代码刚刚将ID放在表中:

DELETE FROM [dbo].[Publication.Person.Include]
    WHERE MemberID = @MemberID AND
          PMID IN (SELECT PMID FROM #pmids);