0

我在下面写了这个触发器。它正在生成错误COUNT(*) From。我希望当使用此触发器将任何行插入表“用户”时,分配中当前存在的文件夹应分配给用户。在此处输入图像描述

例如:我向表中添加新行Users假设userD。然后在此触发器的帮助下,默认情况下,像folderA, folderB, folderC应该分配给文件夹一样userD的文件夹。Visible我在下面写了这个触发器,但它是 givig 错误Count(*) From

CREATE TRIGGER Trigger_Insert ON Users
FOR INSERT
AS
    declare @userid int;
    declare @username nvarchar(50);
    declare @useremail nvarchar(50);
    declare @userpassword nvarchar(50);

    select @userid=i.user_id from inserted i;   
    select @username=i.user_name from inserted i;   
    select @useremail=i.user_email from inserted i; 
    select @userpassword=i.user_password from inserted i;
    DECLARE @intFlag INT
    SET @intFlag =1
    WHILE (@intFlag <=COUNT(*) FROM Assignments;)  // Error Here
    BEGIN
       insert into UAssignment_Rights(
       ua_rights_id,ua_rights_name,assignment_id,user_id) 
       values(@userid,'Visible','','');
       SET @intFlag = @intFlag + 1
       PRINT 'AFTER INSERT trigger fired.'
    END 
GO

你能帮我解决这个问题吗?

4

2 回答 2

3

已更新答案以符合评论中的信息。

我的观点是,大多数时候您不需要 Sql Server 中的循环或游标。通常基于集合的方法更简单、更快。在这种情况下,您可能会使用insert不插入固定值而是插入结果的形式select

CREATE TRIGGER Trigger_Insert ON Users
FOR INSERT
AS
-- this is mandatory in trigger - you do not want @@rowcount reported to applications
-- to change as a result of statement in trigger (all of them, including set and select)

    set nocount on

-- You can simply take assignment_id directly from Assignments table
    insert into UAssignment_Rights(ua_rights_name, assignment_id, user_id)
    select 'Visible', a.assignment_id, i.user_id
      from Inserted i
     cross join dbo.Assignments a

    PRINT 'AFTER INSERT trigger fired.'
GO

PS笛卡尔积是无连接条件连接的结果。这意味着返回的行是左表中每一行与右表中每一行的所有可能组合。

于 2013-08-29T14:59:24.033 回答
2

COUNT(*)只能用作SELECTorHAVING语句的一部分,有关聚合函数的更多信息,请参阅 MSDN

如果Assignments不会作为WHILE循环的一部分更改,请尝试替换...

WHILE (@intFlag <=COUNT(*) FROM Assignments;)  // Error Here

和...

DECLARE @AssignmentsCount INT
SELECT @AssignmentsCount = COUNT(*) FROM Assignments
WHILE @intFlag <= @AssignmentsCount

这意味着COUNT(*)只执行一次。

但是,如果循环期间的数量Assignments 可能会发生变化,请将其替换为...

WHILE @intFlag <= (SELECT COUNT(*) FROM Assignments)
于 2013-08-29T13:06:10.770 回答