插入删除的数据,加上一些硬编码的值,输出语句
我想将行从一个表移动到另一个表,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
声明?
那么,delete_output_test
没有列名为4
或thing4
但delete_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 |
+--------+-----------+--------+--------+
的要求是有点好奇,但我认为你可以使用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
有其他列的空间。
这似乎在向相反的方向移动数据......从delete_output_test2到delete_output_test。我错了吗? – mac9416
我不知道为什么它没有发生,我尝试。谢谢! – mac9416
@ mac9416乐意帮忙! – SqlZim
好吧,那很酷。 –