如何在一个查询中将OUTPUT的结果插入到同一表中?

时间:2019-05-06 15:59:53

标签: sql sql-server tsql sql-update sql-insert

我有一个名为ItemTable的表,该表具有以下列:

ID (identity col int), primary key, foreign key constraint with ProductTable

Col (varchar(50))

ColOther (varchar(50))

Latest (bit)

Time (autogenerated datetime)

我正在查询:

UPDATE ItemTable
SET Col = 'new', ColOther = 'newother'
OUTPUT deleted.Col, deleted.ColOther
WHERE ID = 100;

哪个行更新得很好,并给出正确的输出:

| Col       | ColOther |
| --------- |:--------:|
| old       | oldother |

我想将此输出(和常量INSERTLatest = 0传递到同一ItemTable语句中的同一UPDATE < / p>

我尝试过:

INSERT INTO ItemTable (Col, ColOther, Latest)
UPDATE ItemTable
SET Col = 'new', ColOther = 'newother'
OUTPUT deleted.Col, deleted.ColOther, 0
WHERE ID = 100;

哪个给出错误:

  

关键字“ UPDATE”附近的语法不正确。

并且:

UPDATE ItemTable
SET Col = 'new', ColOther = 'newother'
OUTPUT deleted.Col, deleted.ColOther, 0 INTO ItemTable
WHERE ID = 100;

哪个给出错误:

  

OUTPUT INTO子句的目标表“ ItemTable”不能打开   (主键,外键)关系的任一侧。找到了   参考约束'FK_ProductTable_ItemTable'。

1 个答案:

答案 0 :(得分:2)

您无法在单个语句中做到这一点。
您必须使用一条语句进行更新,而另一条语句进行插入。
但是,您可以在事务中完成此操作,因此,如果插入失败,则可以回滚更新:

DECLARE @updated TABLE (Col varchar(50), ColOther varchar(50))

BEGIN TRANSACTION
BEGIN TRY

UPDATE ItemTable
SET Col = 'new', ColOther = 'newother'
OUTPUT deleted.Col, deleted.ColOther INTO @updated
WHERE ID = 100

INSERT INTO ItemTable (Col, ColOther, Latest)
SELECT Col, ColOther, 0
FROM @updated

COMMIT TRANSACTION
END TRY

BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
END CATCH