日期:2014-05-18  浏览次数:20433 次

批量处理时的触发器问题
建立触发器如下:
ALTER   TRIGGER   TG_InsertEmployee   ON   [SynchEmployeeTemp]      
FOR     INSERT    
AS
BEGIN   TRAN   AddUsers
/*   如果存在相同编号,则返回   */
IF   EXISTS   (SELECT   1   FROM   Users   a   INNER   JOIN   INSERTED   b   ON   a.UserCode   =   b.UserCode)
RETURN

/*   产生用户名   开始   */
DECLARE   @Gender   nvarchar(10),   @Val2   DATETIME,   @Birthday   NVARCHAR(20),   @LimitAge   INT,   @NowYear   INT,   @Age   INT,   @Init   INT,   @Terminal   INT,   @I   INT
,   @MaxNo   NVARCHAR(50),   @UserName   NVARCHAR(50),   @PassWord   NVARCHAR(50)
SELECT   @Gender   =   Gender,   @Val2   =   Birthday,   @PassWord   =   SUBSTRING(ISNULL(CardID,   '000000000 '),   0,   9)   FROM   INSERTED

IF   @Val2   IS   NULL
SET   @Val2   =   '1900-01-01 '
if   @Gender   <>   '1 '   AND   @Gender   <>   '2 '
SET   @Gender   =   '1 '

SELECT   @Birthday   =   CAST(DATEPART(year,   @Val2)   AS   NVARCHAR(10)),   @LimitAge   =   60,   @NowYear   =   DATEPART(YEAR,   GETDATE()),   @Init   =   10,   @Terminal   =   10
SET   @Age   =   @NowYear   -   CAST(DATEPART(year,   @Val2)   AS   NVARCHAR(10))

if   @Gender   =   '1 '
    SET   @limitage   =   60;
else   if   @Gender   =   '2 '
    SET   @LimitAge   =   55;

SET   @I   =   (@limitage   -   @age)   /   5
if   @i   <   0
SET   @i   =   0;

SELECT   @Init   =   10   +   ((@NowYear   -   2001)   /   5),   @Terminal   =   10   +   @I

--BEGIN   TRAN   GetMaxEmployeeNo
IF   NOT   EXISTS(SELECT   1   FROM   MaxEmployeeNo)
BEGIN
select   @MaxNo   =   max(EmployeeNo)   from   employeeinfo   with(TABLOCKX)
print   '最大值: '   +   @maxno
SET   @MaxNo   =   SUBSTRING(@MaxNo,   1,   5)
INSERT   INTO   MaxEmployeeNo(CurrentMaxNo)   VALUES(@MaxNo)
END
ELSE
SELECT   @MaxNo   =   CurrentMaxNo   FROM   MaxEmployeeNo
select   *   from   MaxEmployeeNo
SET   @MaxNo   =   CAST(@MaxNo   AS   INT)   +   1
PRINT   @MaxNo
SET   @MaxNo   =   left(CAST((CAST(@MaxNo   AS   INT)   +   1)   AS   NVARCHAR(5))   +   '00000 ',   5)
UPDATE   MaxEmployeeNo   SET   CurrentMaxNo   =   CurrentMaxNo   +   1
--IF   @@ERROR   <>   0
-- ROLLBACK   TRAN   GetMaxEmployeeNo
--ELSE
-- COMMIT   TRAN   GetMaxEmployeeNo

print   '初始值: '   +   CAST(@init   AS   NVARCHAR(10))

PRINT   '加值后的最大值: '   +   @MaxNo