Sql 如何从表中选择记录并插入到另一个表中?

Sql 如何从表中选择记录并插入到另一个表中?,sql,Sql,我想从表1中选择最后一条记录并插入到另一个表中 Insert into table2 values(select top 1 col1,col2 from table1 order by id desc). 我知道向表中添加值需要在cotation中。但在哪里添加?在SQL中,向表中插入数据基本上有两种方法:一种是一次插入一行,另一种是一次插入多行。让我们逐一来看它们: INSERT INTO table_name (column1, column2, ...) VALUES ('value1

我想从表1中选择最后一条记录并插入到另一个表中

Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).

我知道向表中添加值需要在cotation中。但在哪里添加?

在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)
insert into table2 (col_a, col_b, col_c, col_d)
select top 1 col1, col2, 'foo', 'bar'
from table1
order by id desc
或者您可以使用如下语法:

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)
insert into table2 (col_a, col_b, col_c, col_d)
select top 1 col1, col2, 'foo', 'bar'
from table1
order by id desc

当然,假设列数据类型匹配,这一切都可以工作。

您可以选择文本来填充
表1
无法提供的其他列,类似于以下内容:

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


所选列的数量和类型必须与插入列列表中列的数量和类型匹配。

这意味着
col1
col2
列在两个表之间的名称相同。可能不是这样。字符文字需要用单引号括起来,而不是双引号:
VALUES('value1',…)