如果我有两个列num1和num2的表Test,并且下面的触发器只是在num1的插入上增加num2:
DECLARE @PROC_NEWNUM1 VARCHAR (10)
DECLARE @NEWNUM2 numeric(20)
DECLARE my_Cursor CURSOR FOR SELECT num1 FROM INSERTED;
OPEN my_Cursor
FETCH NEXT FROM my_Cursor into @PROC_NEWNUM1
WHILE @@FETCH_STATUS = 0
BEGIN
select @NEWNUM2 = MAX(num2) from TEST
if @NEWNUM2 is null
Begin
set @NEWNUM2 = 0
End
set @NEWNUM2 = @NEWNUM2 + 1
UPDATE TEST SET num2 = @NEWNUM2 WHERE num1 = @PROC_NEWNUM1
FETCH NEXT FROM my_Cursor into @PROC_NEWNUM1
END
CLOSE my_Cursor
DEALLOCATE my_Cursor
有没有办法使用基于集合的方法重写上述内容?
(如果有人想知道我为什么这样做,这里是背景:
SQL Server A trigger to work on multiple row inserts)
没有使用Row_Number的临时表的解决方案(仅限Sql 2005):
SELECT @MAXNUM2 = MAX(num2) FROM TEST
if @MAXNUM2 IS NULL
BEGIN
SET @MAXNUM2=0
END
UPDATE TEST
SET num2 = @MAXNUM2 + SubQuery.R
FROM
(
SELECT num1, ROW_NUMBER() OVER (ORDER BY num1) as R FROM inserted
)
SubQuery
INNER JOIN TEST on SubQuery.num1 = TEST.num1
最佳答案
DECLARE @MAXNUM2 numeric(20)
-- First make an auto increment table starting at 1
DECLARE @tmp table
(
aNum int identity(1,1),
pInsNum varchar(10)
)
INSERT INTO @tmp (pInsNum)
SELECT num1 FROM INSERTED;
-- Now find offset
SELECT @MAXNUM2 = MAX(num2) FROM TEST
IF @MAXNUM2 is null
BEGIN
SET @MAXNUM2 = 0
END
-- Do update
UPDATE TEST
SET num2 = @MAXNUM2 + aNum
FROM TEST
INNER JOIN @tmp t ON t.pInsNum = TEST.num1
注意:我无法测试这个,可能有拼写错误.
另外,我确定有一个使用ROWNUMBER的非临时表解决方案,但我懒得去查找语法.但您可以使用此作为指导来获得该答案,而不是使用临时表来使数字从1到N使用ROWNUMBER并将其添加到偏移量(@ maxnum2)