2017-08-03 52 views
2

我想將行從一個表移動到另一個表,delete from [foo] output deleted.[col] into [bar] (col)看起來是一個不錯的選擇。插入刪除的數據,加上一些硬編碼的值,輸出語句

但列不相同。所以我想插入一些硬編碼的值(理想的編程決定的值)到目標表中。

我設置了幾張表來演示。

create table delete_output_test (
    thing1 int not null, 
    thing2 varchar(50), 
    thing3 varchar(50) 
) 

create table delete_output_test2 (
    thing1 int not null, 
    thing2 varchar(50), 
    thing3 varchar(50), 
    thing4 int 
) 

insert into delete_output_test values (0, 'hello', 'world'), 
             (1, 'it''s', 'me'), 
             (2, 'i', 'was'), 
             (3, 'wondering', 'if') 

現在從一個表移動到罰款,如果我不是太貧窮的另一個作品...

delete from delete_output_test2 
output deleted.thing1, 
     deleted.thing2, 
     deleted.thing3 
into delete_output_test 
     (thing1, 
     thing2, 
     thing3) 

但如果我要來填充最後一列是什麼?

delete from delete_output_test2 
output deleted.thing1, 
     deleted.thing2, 
     deleted.thing3 
into delete_output_test 
     (thing1, 
     thing2, 
     thing3, 
     4) 

附近有語法錯誤 '4'。期待'。',ID,PSEUDOCOL或QUOTED_ID。

我對SQL相當陌生,所以我甚至不確定這些東西是什麼。

那麼,爲什麼我不能硬編碼插入的值?或者,如果我想變得聰明,甚至用4替換一些select聲明?

回答

7

那麼,delete_output_test沒有列名爲4thing4delete_output_test2呢。所以,你可以這樣做:

delete from delete_output_test 
output deleted.thing1, 
     deleted.thing2, 
     deleted.thing3, 
     4 
into delete_output_test2 
     (thing1, 
     thing2, 
     thing3, 
     thing4); 
select * from delete_output_test2; 

rextester演示:http://rextester.com/CVZOB61339

回報:

+--------+-----------+--------+--------+ 
| thing1 | thing2 | thing3 | thing4 | 
+--------+-----------+--------+--------+ 
|  0 | hello  | world |  4 | 
|  1 | it's  | me  |  4 | 
|  2 | i   | was |  4 | 
|  3 | wondering | if  |  4 | 
+--------+-----------+--------+--------+ 
+0

我不知道爲什麼它沒有發生,我嘗試。謝謝! – mac9416

+1

@ mac9416樂意幫忙! – SqlZim

+0

好吧,那很酷。 –

1

的要求是有點好奇,但我認爲你可以使用CTE或子查詢做到這一點:

with todelete as (
     select dot.*, 4 as col4 
     from delete_output_test 
    ) 
delete from todelete 
    output deleted.thing1, deleted.thing2, deleted.thing3, deleted.col4 
    into delete_output_test2(thing1, thing2, thing3, col4); 

你需要確保delete_output_test有其他列的空間。

+0

這似乎在向相反的方向移動數據......從delete_output_test2到delete_output_test。我錯了嗎? – mac9416