【问题标题】:Insert into select from multiple tables(join? ) and constants从多个表中插入选择(加入?)和常量
【发布时间】:2014-03-05 05:47:43
【问题描述】:

我正在尝试使用来自其他表和常量的值进行插入。我在 SO 上找到了部分答案,但我无法完成存储过程。我应该做类似的事情

INSERT INTO table1(value1, value2, value3, value4)
SELECT 
    @value1,
    value2,
    value3,
    @value4 
FROM table2 WHERE table2.id = @value2; -- not sure

但我也必须使用某种连接来从第三个表中获取数据,但我不知道如何。

我有 3 张桌子。 我想这样插入

INSERT INTO table1(field1, field2, field3, field4)

至于价值观

field1 = @field1
SELECT field2_type FROM table2 WHERE field2ID = @field2 -- field2
SELECT field3_type FROM table3 WHERE field3ID = @field3 -- field3
field4 = @field4

我使用的是 SQL Server 2012

table1 看起来像:

ID       int, PK
Name     varchar
Function int
Type     int
Age      int

table2 看起来像:

FunctionID           int
FunctionDescription  varchar

table3 看起来像:

TypeID               int
TypeDescription      varchar

【问题讨论】:

    标签: sql-server select join insert


    【解决方案1】:

    非常不清楚你说了什么,但如果你想得到全部,请使用 UNION 或使用 JOIN

    INSERT INTO table1
    SELECT *
    FROM table2 
    UNION
    SELECT * FROM table3
    

    【讨论】:

      【解决方案2】:

      我设法找到了答案。如果其他人正在寻找它:

      INSERT INTO table1(field1, field2, field3, field4)
      select
      field1 = @field1,
      field2=  (SELECT TOP 1 field2_type FROM table2 WHERE field2ID = @field2 order by (select NULL)),
      field3 = (SELECT TOP 1 field3_type FROM table3 WHERE field3ID = @field3 order by (select NULL)),
      field4 = @field4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        相关资源
        最近更新 更多