如何使用触发器获得所需的输出

时间:2013-09-20 12:16:32

标签: sql sql-server-2008 stored-procedures triggers

我有一张记录表

create table rstbljobs  
(  
AutoID identity(1,1),  
AssignedToRstEmpID int,  
priorityid int,  
Jobstatusid int  
)


Insert into rstbljobs values ( 147,202,374)  
Insert into rstbljobs values ( 169,214,374)  
Insert into rstbljobs values ( 170,202,374)  
Insert into rstbljobs values ( 176,202,374)  
Insert into rstbljobs values ( 182,202,374)  
Insert into rstbljobs values ( 147,214,374)  
Insert into rstbljobs values ( 183,202,374)  
Insert into rstbljobs values ( 170,214,374)  
Insert into rstbljobs values ( 182,214,374)  
Insert into rstbljobs values ( 170,202,374)  
Insert into rstbljobs values ( 147,214,374)  
Insert into rstbljobs values ( 147,202,374)  
Insert into rstbljobs values ( 169,202,374)  
Insert into rstbljobs values ( 169,214,374)  

我有另一张表UsersRSDesk

Create table UsersRSDesk  
(  
userid int,  
IsRecruit bit,  
status bit,  
noofhighprtjobs varchar(50)  
)

记录是

insert into UsersRSDesk values (147,1,0,null)  
insert into UsersRSDesk values (169,1,0,null)  
insert into UsersRSDesk values (170,1,0,null)  
insert into UsersRSDesk values (176,1,0,null)  
insert into UsersRSDesk values (182,1,0,null)  
insert into UsersRSDesk values (183,1,0,null)  

查询如下:

select AssignedToRstEmpID,COUNT(AssignedToRstEmpID)as Noofcount from RStblJobs 
group by AssignedToRstEmpID

从上面的查询中,我希望将rstbljobs中的noofcount插入到usersrsdesk.noofhighprtjobs列中。每当我更新rstbljobs表时,同样的计数也应该反映在这里。

1 个答案:

答案 0 :(得分:0)

简短的回答是你可能不应该这样做。存储计算值通常不是OLTP数据库的良好实践(对于OLAP来说这是非常正常的),相反,如果这是您需要定期访问的数字,那么您应该考虑爬行视图:

CREATE VIEW dbo.UserJobs
AS
    SELECT  AssignedToRstEmpID,
            Noofcount = COUNT(AssignedToRstEmpID) 
    FROM    RStblJobs 
    GROUP BY AssignedToRstEmpID;

然后,您可以使用此视图按如下方式计算:

SELECT  *
FROM    UsersRSDesk
        LEFT JOIN dbo.UserJobs
            ON UserJobs.AssignedToRstEmpID = UsersRSDesk.userid;

如果您希望这是性能消耗,那么您可以创建一个索引视图:

CREATE VIEW dbo.UserJobs
WITH SCHEMABINDING
AS
    SELECT  AssignedToRstEmpID,
            Noofcount = COUNT_BIG(*) 
    FROM    dbo.RStblJobs 
    GROUP BY AssignedToRstEmpID;

GO
CREATE UNIQUE CLUSTERED INDEX IX_UserJobs_AssignedToRstEmpID 
  ON dbo.UserJobs (AssignedToRstEmpID);

使用索引视图,计数将存储在聚簇索引中,但您需要使用NOEXPAND提示来确保使用索引。

SELECT  *
FROM    UsersRSDesk
        LEFT JOIN dbo.UserJobs (NOEXPAND)
            ON UserJobs.AssignedToRstEmpID = UsersRSDesk.userid;

<强> Example on SQLFiddle