在具有2个不同子查询的临时表中插入两列

时间:2014-06-26 12:43:05

标签: sql sql-server

是否可以在具有2个不同子查询的临时表中将数据插入两个列?

我试过以下

CREATE TABLE #Temp (
FromPlanInvtId BIGINT
,ToPlanInvtId BIGINT
)

INSERT INTO #Temp (
FromPlanInvtId 
,ToPlanInvtId
)
VALUES (
(SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 65)
,(SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 214)
)

此处两个子查询都会返回多个值

还有其他办法吗?

2 个答案:

答案 0 :(得分:1)

是。使用insert . . . select

INSERT INTO #Temp (FromPlanInvtId, ToPlanInvtId)
    SELECT (SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 65),
           (SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 214);

这假设每个子查询最多返回一行。否则,您将收到一个错误,即"子查询返回多行"。

编辑:

如果子查询返回多个值,那么您可以获得以下所有组合:

INSERT INTO #Temp (FromPlanInvtId, ToPlanInvtId)
    SELECT t1.PlanInvtId , t2.PlanInvtId 
    FROM (SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 65
         ) t1 CROSS JOIN
         (SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 214
         ) t2;

答案 1 :(得分:0)

Drop table #Temp 
CREATE TABLE #Temp (
FromPlanInvtId BIGINT
,ToPlanInvtId BIGINT
)

INSERT INTO #Temp (
FromPlanInvtId 
,ToPlanInvtId
)
Select

(SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 65),
(SELECT PlanInvtId FROM PR_PLANINVESTMENTS WHERE PlanId = 214)