OUTPUT 子句可以创建表吗?

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 或者我是否必须在运行语句之前确保它已经存在?

Aar*_*and 7

AFAIK,目标表必须存在,尽管文档不是明确的,可能应该存在。我在语法图中看不到任何支持任何类型的扩展以同时创建输出表的内容。


小智 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)

我知道这个答案来的有点晚,但我希望它可以帮助遇到类似问题的其他人。脚本编写愉快!