【问题标题】:How to select the record from table and insert into another table?如何从表中选择记录并插入另一个表?
【发布时间】:2012-01-23 12:31:01
【问题描述】:

我想从 table1 中选择最后一条记录并插入到另一个表中。这是我的查询。

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

我知道要将值添加到表中,需要在 coation 中。但是在哪里添加?

【问题讨论】:

    标签: sql


    【解决方案1】:

    您可以选择文字来填充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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这意味着col1col2 列在两个表之间是相同的名称。情况可能并非如此。
      • 字符文字需要用单引号括起来,而不是双引号:VALUES ('value1', ...)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 2013-05-25
      • 2014-02-17
      • 2011-10-23
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多