解决方法是使用表变量并使用 WHILE 循环遍历行。以下是使用 FROM 解决方法的 UPDATE 示例:
DROP TABLE IF EXISTS dbo.table1
GO
DROP TYPE IF EXISTS dbo.type1
GO
CREATE TABLE dbo.table1
(Id INT NOT NULL PRIMARY KEY NONCLUSTERED,
c2 INT NOT NULL,
LastUpdated DATETIME2 NOT NULL DEFAULT (SYSDATETIME()))
WITH (MEMORY_OPTIMIZED=ON)
GO
CREATE TYPE dbo.type1 AS TABLE
(Id INT NOT NULL,
c2 INT NOT NULL,
RowID INT IDENTITY,
INDEX ix_RowID (RowID DESC))
WITH (MEMORY_OPTIMIZED=ON)
GO
CREATE TRIGGER dbo.tr_table1
ON dbo.table1
WITH NATIVE_COMPILATION, SCHEMABINDING
AFTER UPDATE
AS BEGIN ATOMIC WITH
(
TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'us_english'
)
-- original UPDATE with FROM statement:
--UPDATE dbo.table1
--SET LastUpdated = SYSDATETIME()
--FROM dbo.table1 t JOIN Inserted i ON t.Id=i.Id
DECLARE @tv dbo.type1
INSERT @tv (Id, c2)
SELECT Id, c2 FROM Inserted
-- workaround that iterates over the rows in the table variable, simulating a cursor:
DECLARE @max INT = SCOPE_IDENTITY()
DECLARE @i INT = 1
DECLARE @Id INT
WHILE @i <= @max
BEGIN
SELECT @Id = Id
FROM @tv
WHERE RowID=@i
UPDATE dbo.table1
SET LastUpdated = SYSDATETIME()
WHERE Id = @Id
SET @i += 1
END
END
GO
INSERT dbo.table1 (Id, c2) VALUES (1,2)
INSERT dbo.table1 (Id, c2) VALUES (2,2)
GO
SELECT * FROM dbo.table1
GO
UPDATE dbo.table1
SET c2 = 3
GO
SELECT * FROM dbo.table1
GO