我不得不对触发器进行更改,并假设运行如下所示的更新查询会使触发器对所有匹配的行执行。但相反,它只更新它找到的记录。
UPDATE someTable SET someField = someField WHERE someField = 'something';
作为一种快速解决方案,我使用游标创建了以下查询以循环记录并更新每一行。它有效,幸运的是我没有一个非常大的数据集,因此它不需要太长时间,但它似乎不是最好的解决方案。
DECLARE @id INT;
DECLARE queryCursor CURSOR FOR
SELECT id FROM someTable WHERE someField='something'
OPEN queryCursor
FETCH NEXT FROM queryCursor INTO @id
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE someTable SET someField = someField WHERE id = @id
FETCH NEXT FROM queryCursor INTO @id
END
CLOSE queryCursor
DEALLOCATE queryCursor
有没有更好的方法来获取在SQL Server中的多行上执行的触发器?
编辑:来自触发器的代码
FOR INSERT, UPDATE
AS
IF UPDATE (LineNumber)
OR UPDATE(LineService)
Begin
DECLARE @CDL VARCHAR(50)
DECLARE @LN VARCHAR(100)
DECLARE @A VARCHAR(25)
SELECT @CDL = CommonDataLink FROM INSERTED
SELECT @A = LineService FROM INSERTED
SET @LN = @CDL + @A
UPDATE CommonData SET ReportedLineNo = @LN WHERE CommonDataLink = @CDL
End
答案 0 :(得分:4)
您必须根据需要使用特殊表格INSERTED
:
更新代码
FOR INSERT, UPDATE
AS
IF UPDATE (LineNumber)
OR UPDATE(LineService)
Begin
DECLARE @CDL VARCHAR(50)
DECLARE @LN VARCHAR(100)
DECLARE @A VARCHAR(25)
SELECT @CDL = CommonDataLink FROM INSERTED
SELECT @A = LineService FROM INSERTED
SET @LN = @CDL + @A
UPDATE A
SET ReportedLineNo = B.LineService + B.CommonDataLink
FROM CommonData A
INNER JOIN INSERTED B
ON A.CommonDataLink = B.CommonDataLink
End