我有一个更新一条记录的查询,只有一条记录。是否有方法可以在同一查询中更新Id,例如插入时选择ScopeIdentity。
UPDATE Task
SET MyTime = GetDate(), MyUserId = @userid
FROM (select top 1 table where SomeStuff)
Select Lastrow that just got updated.
答案 0 :(得分:5)
是的,请使用OUTPUT子句
示例:
UPDATE Task
SET MyTime = GetDate(), MyUserId = @userid
OUTPUT INSERTED.MyID
FROM (select top 1 table where SomeStuff)
或
DECLARE @MyTableVar TABLE (...
...
UPDATE Task
SET MyTime = GetDate(), MyUserId = @userid
OUTPUT INSERTED.MyID INTO @MyTableVar
FROM (select top 1 table where SomeStuff)
答案 1 :(得分:3)
根据您的操作,您可能需要使用OUTPUT
的表格语法。可能是指定临时表/表变量。
DECLARE @T TABLE
(
MyID INT NOT NULL
)
UPDATE Task
SET MyTime = GetDate(), MyUserId = @userid
OUTPUT INSERTED.MyID INTO @T
FROM (/* your FROM clause here */) Task
gbn在我之前进行了一次编辑,基本上与上面说的一样。我想补充一点,另一种方法是首先获取ID,然后按ID更新。此外,TOP 1应该几乎总是与ORDER BY
一起使用。
-- You may need to clean up the error handling. I just wanted
-- to put something simple in to remind that it is necessary.
DECLARE @userid INT; SET @userid = /* e.g., */ 1234
BEGIN TRANSACTION
IF @@ERROR <> 0 RETURN
DECLARE @TaskID INT
SET @TaskID = (SELECT TOP 1 TaskID FROM Task WITH (UPDLOCK) ORDER BY /* e.g., */ TaskID) -- TaskID should be the PK of MyTable. Must be unique.
IF @@ERROR <> 0 BEGIN ROLLBACK TRANSACTION RETURN END
UPDATE Task
SET MyTime = GETDATE(), MyUserId = @userid
WHERE TaskID = @TaskID
COMMIT TRANSACTION
答案 2 :(得分:0)
一个简单的方法:
UPDATE TOP (1) Task
SET MyTime = GetDate(), MyUserId = @userid
OUTPUT INSERTED.Id ,INSERTED.Sth
WHERE Stuff=SomeStuff