我想从table1中选择最后一条记录并插入到另一个表中。这里是我的查询。如何从表中选择记录并插入到另一个表中?
Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).
我知道为表中添加值需要在cotation.But在哪里添加?
我想从table1中选择最后一条记录并插入到另一个表中。这里是我的查询。如何从表中选择记录并插入到另一个表中?
Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).
我知道为表中添加值需要在cotation.But在哪里添加?
您可以选择文字在其他列填补table1
不能提供,这样的事情:
insert into table2 (col_a, col_b, col_c, col_d)
select top 1 col1, col2, 'foo', 'bar'
from table1
order by id desc
任何列不列列表名称将得到默认值,或null
如果没有定义默认值。
所选列的数量和类型必须与插入列列表中列的数量和类型相匹配。
在SQL中,基本上有两种将数据插入表的方法:一种是一次插入一行,另一种是一次插入多行。让我们来看看他们每个人单独:
INSERT INTO table_name (column1, column2, ...)
VALUES ('value1', 'value2', ...)
第二种INSERT INTO允许我们多行插入表中。与前面的例子不同,我们通过指定所有列的值来插入单行,现在我们使用SELECT语句指定要插入表中的数据。如果您在考虑这是否意味着您正在使用来自其他表格的信息,那么您是正确的。语法如下:
INSERT INTO table1 (column1, column2, ...)
SELECT t2.column3, t2.column4, ...
FROM table2 t2
所以,在你的情况下,你可以做这样的:
Insert into table2
select top 1 t1.col1,t1.col2 from table1 t1 order by id desc
或者你可以用你的语法如下:
declare @col1 type_of_col1, @col2 type_of_col2
select top 1 @col1 = t1.col1, @col2 = t1.col2 from table1 t1 order by id desc
Insert into table2 values(@col1, @col2)
Offcourse,这一切都假定列数据类型匹配。
这意味着'col1'和'col2'列是两个表之间的相同名称。情况可能并非如此。 – fge 2011-12-19 11:00:16
@fge offcourse,我假设.. – 2011-12-19 11:02:11
字符文字需要用单引号引起来,而不是双引号:'VALUES('value1',...)' – 2011-12-19 11:02:42
+1感谢您保持简单的答案! – 2011-12-19 11:22:01