简体   繁体   English

使用output&into子句将数据插入两个表

[英]Using output&into clause to insert data to two tables

i would like to move some staging data to production table and delete staging data and inserting history data for production table at the same time if it is possible. 我想将一些登台数据移至生产表,并在可能的情况下同时删除登台数据并同时为生产表插入历史数据。 i want to do something like below: 我想做下面的事情:

DELETE FROM _stagingTable
OUTPUT deleted.idTest, deleted.textTest
INTO _productionTable(idTest,textTest)
--Below is what im not sure
OUTPUT 'Add',deleted.idTest, deleted.textTest
INTO _productionTableHistory(typeTest, idTest, textTest)

Is it possible to use output clause more than once? 是否可以多次使用output子句? Or what do you suggest me to do? 还是您建议我做什么?

Thanks in advance 提前致谢

The answer is no you cannot directly do what you want. 答案是否定的,你不能直接做你想做的事。

If you do not want to use a trigger solution and you do not want a query based on a primary key then I think you want a temp table. 如果您不想使用触发器解决方案,并且不想基于主键进行查询,那么我认为您需要一个临时表。

Output into #TempHoldTable, then insert into table1 from #TempHoldTable and insert into table2 from #TempHoldTable. 输出到#TempHoldTable,然后从#TempHoldTable插入table1,然后从#TempHoldTable插入table2。

I think this is the idea: 我认为这是个主意:

DELETE FROM _stagingTable
    OUTPUT deleted.idTest, deleted.textTest
    INTO _productionTable(idTest, textTest);

INSERT INTO _productionTableHistory(typeTest, idTest, textTest)
    SELECT 'Add', idTest, textTest
    FROM _productionTable pt;

These are two separate statements. 这是两个单独的语句。 You can wrap them into a single transaction, if you need to. 如果需要,可以将它们包装为一个事务。

If you are concerned about data in _productionTable , then truncate it before using it in the output clause. 如果您担心_productionTable数据, _productionTableoutput子句中使用它之前将其截断。 Given that it starts with an underscore, I find it hard to believe that the intention is not a temporary place just for this statement, but I don't know the naming conventions being used. 鉴于它以下划线开头,所以我很难相信该意图并不是仅用于此语句的临时位置,但我不知道所使用的命名约定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM