从临时表中删除记录时删除的所有记录

时间:2014-11-24 06:39:43

标签: sql sql-server

我有一个存储过程,我传递一个documentIDs字符串,并且它应该删除其roleID = @roleID的documentID,而是删除所有基于roleID的记录,我想要做的就是根据roleID

从表中删除documentID

我的sp是

ALTER PROCEDURE sp_RemoveDocumentIDsFromRole
(
@roleID int,
@group_name varchar(50),
@DocumentIDString varchar(500),
@group_display_name varchar(50)
)
as
UPDATE [master_groups] 
set group_name = @group_name, @group_display_name = @group_display_name
where roleID = @roleID

-- Creating Variables
DECLARE @numberLength int
DECLARE @numberCount int
DECLARE @TheDocumentIDs VarChar(500)

DECLARE @sTemp VarChar(100) -- to hold single characters

    -- Creating a temp table
DECLARE @T TABLE 
(
    TheDocumentIDs VarChar(500)
)
--Initializing Variables for counting 
SET @numberLength = LEN (@DocumentIDString)
SET @numberCount = 1
SET @TheDocumentIDs = ''

--Start looping through the keyword ids
WHILE (@numberCount <= @numberLength)

BEGIN
SET @sTemp = SUBSTRING (@DocumentIDString, @numberCount, 1)
    IF (@sTemp = ',')
        BEGIN
            INSERT @T(TheDocumentIDs) VALUES (@TheDocumentIDs)
            SET @TheDocumentIDs = ''
        END
    IF (@sTemp <> ',')
        BEGIN
            SET @TheDocumentIDs = @TheDocumentIDs + @sTemp
        END
        SET @numberCount = @numberCount + 1
END 

declare @rLevel int
set @rLevel = 0

delete from [master_group_document_relations] where exists(select documentID = @TheDocumentIDs from @T) and roleID = @roleID

更新:示例数据 Sample Data

2 个答案:

答案 0 :(得分:0)

不确定您在 @TheDocumentIDs 中获得了什么,但我认为它应该适合您。

首先提到 @Chris ,你应该把条件检查到where子句,而documentIds是一个应该与 IN 一起使用的id的列表条件而非平等,这就是您需要或使用 sp_executesql 或将ID填入临时表的原因。

         EXECUTE sp_executesql 
          N'delete from [master_group_document_relations] 
            where documentID IN (@TheDocumentIDs) 
               and roleID = @roleID',
          N'@TheDocumentIDs varchar(500), @roleID int',
          @DocumentIDString,
          @roleID;

或试试这个

            delete from [master_group_document_relations] 
            where documentID IN (SELECT TheDocumentIDs FROM @T) 
               and roleID = @roleID

答案 1 :(得分:0)

如果您要删除master_group_document_relations documentID TheDocumentIDs @t roleID@roleID等于DELETE T1 FROM [master_group_document_relations] AS T1 WHERE EXISTS(SELECT 1 FROM @T AS T2 WHERE T1.documentID = T2.TheDocumentIDs) AND roleID = @roleID 的记录{}试试这个:

{{1}}