Ken*_*her 7 sql-server-2008 sql-server output-clause
我正在做这样的更新:
UPDATE dbo.Table1
SET BirthDate = b.BirthDate
FROM Table1 a
JOIN Table2 b
ON a.ID = b.ID
Run Code Online (Sandbox Code Playgroud)
我想使用 OUTPUT 子句来备份我的更改。
UPDATE dbo.Table1
SET BirthDate = b.BirthDate
OUTPUT
inserted.Id, inserted.BirthDate AS New_BirthDate,
deleted.BirthDate AS Old_BirthDate
INTO OutputTable
FROM Table1 a
JOIN Table2 b
ON a.ID = b.ID
Run Code Online (Sandbox Code Playgroud)
我想知道的是 OUTPUT 子句是否有办法创建表 OutputTable 或者我是否必须在运行语句之前确保它已经存在?
小智 5
亚伦伯特兰是对的。该OUTPUT
子句的文档没有明确说明不能使用它来创建表。我遇到了同样的问题。我最终做的是使用两个语句:
--This creates the table with the needed columns without inserting any data.
SELECT TOP 0 [myColumn1], [myColumn2], ...etc
INTO [myNewTable]
FROM [myTable]
--This updates the records and inserts the updated data into the new table.
UPDATE [myTable]
SET [myColumn1] = 'Some Value',
[myColumn2] = 'Some Other Value', ...etc
OUTPUT
[myColumn1], [myColumn2], ...etc
INTO [myNewTable]
FROM [myTable] ...etc.
Run Code Online (Sandbox Code Playgroud)
我知道这个答案来的有点晚,但我希望它可以帮助遇到类似问题的其他人。脚本编写愉快!