在触发器中调用aspnet_Delete_User SP

时间:2012-02-22 21:52:53

标签: sql-server-2008 triggers asp.net-membership

我在学生表中有一个触发器,当我删除学生时删除其他表中的相关记录。我想通过在触发器中调用aspnet_delete_user存储过程来删除学生的成员资格数据。但是如果我删除一个学生就行。如果我在一个查询中卸下多个学生,它就不起作用。

如何将此SP称为多行操作触发器?

2 个答案:

答案 0 :(得分:2)

您必须使用游标或构建动态SQL字符串(使用游标而不这样说)。或者,您可以从存储过程中复制逻辑,看看是否可以将其定制为基于集合 - 我没有查看过程,所以我不确定这是否可行,实用甚至是可能的,但是在将游标或动态SQL添加到触发器之前,这是我尝试做的第一件事。

对于游标,类似这样的东西(我猜你把GUID或其他东西传递给程序,但我不知道):

CREATE TRIGGER dbo.StudentAfterDelete
ON dbo.Students
AFTER DELETE
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @MemberID UNIQUEIDENTIFIER;

  DECLARE c CURSOR LOCAL STATIC FORWARD_ONLY READ_ONLY
    FOR SELECT MemberID FROM deleted;

  OPEN c;

  FETCH NEXT FROM c INTO @MemberID;

  WHILE @@FETCH_STATUS <> -1
  BEGIN
    EXEC dbo.aspnet_delete_user @MemberID;

    FETCH NEXT FROM c INTO @MemberID;
  END

  CLOSE c;
  DEALLOCATE c;
END
GO

动态SQL,同样的假设:

CREATE TRIGGER dbo.StudentAfterDelete
ON dbo.Students
AFTER DELETE
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @sql NVARCHAR(MAX) = N'';

  SELECT @sql += 'EXEC dbo.aspnet_delete_user ''' 
    + CONVERT(VARCHAR(36), MemberID) + ''';' FROM deleted;

  EXEC sp_executesql @sql;
END
GO

但是,预先包含缺少的信息会更有用。不要以为每个使用SQL Server的人都知道aspnet_delete_user的作用。

答案 1 :(得分:2)

也许是这样的:

CREATE TRIGGER TheNameOfTheTrigger
ON YourTableYouWantToTriggerOn
AFTER DELETE 
AS
   DECLARE @yourPrimaryKey int

    DECLARE delete_cursor CURSOR FOR 
    SELECT
        yourPrimaryKey
    FROM
        deleted

    OPEN delete_cursor

    FETCH NEXT FROM delete_cursor 
    INTO @yourPrimaryKey

    WHILE @@FETCH_STATUS = 0
    BEGIN
       EXEC aspnet_delete_user @yourPrimaryKey
       FETCH NEXT FROM delete_cursor INTO @yourPrimaryKey
    END

    CLOSE delete_cursor
    DEALLOCATE delete_cursor
GO

查看更多信息herehere