2

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? Or what do you suggest me to do?

Thanks in advance

2 Answers2

0

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.

Joe C
  • 3,925
  • 2
  • 11
  • 31
-1

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. 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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 2
    This would have a problem of grabbing records from _productionTable that were loaded previous to this 'transaction'. – Joe C May 16 '16 at 14:06
  • @JoeC . . . So empty the table before doing the insert. The `_` suggests that it is a temporary table anyway. – Gordon Linoff May 16 '16 at 14:30
  • 1
    _ does not mean that to me. Without that being specified in the question, production table implies that it will have records from multiple runs. – Joe C May 16 '16 at 14:44