2017-05-23 63 views
-2

我想在临时表@temp从下面表1 &的两个不同的表表2插入数据动态地在临时表中从两个表

表1动态地插入数据:

enter image description here

表2:

enter image description here

Declare @temp table (Pays nvarchar (300), Factory nvarchar (300), Count bigint) 

我试过这个命令,但我有一个错误信息:Subquery returned more than 1 value.

Insert into @temp select (select pays from table1),(select factory,count from table 2 where @Pays=’yes’) 

结果是前人的精力像见下表@temp

enter image description here

谢谢你的帮助。

+1

您如何知道工厂SUX,DRV和HK在法国而不是美国? –

+0

您正在寻找一个选择喂养你的插入,并加入Table1和Table2。顺便说一下,你没有解释这两者是如何相关的。 –

+0

哪里是说'SUX'去'法国'的映射表 –

回答

0

您想让join (documentation here)运行单个select语句。

您可能还需要阅读this因为有表变量(@Table)和临时表(#table)之间的重要区别

0

首先,如果你有没有使用像计数的关键字作为一个属性对,然后用这样的 - > [计数]

DROP TABLE IF EXISTS table1 
 
create table table1 (Pays nvarchar(300)) 
 
DROP TABLE IF EXISTS table2 
 
create table table2 (Factory nvarchar(300), [Count] bigint) 
 

 
/*temp table in sql should be created like this*/ 
 
create table #temp (Pays nvarchar(300),Factory nvarchar(300), [Count] bigint) 
 
/*table variable should be created like this*/ 
 
Declare @temp table (Pays nvarchar (300), Factory nvarchar (300), [Count] bigint) 
 

 

 
insert into #temp(Pays) select Pays 
 
from table1 
 
insert into #temp(Factory,[Count]) select Factory,[Count] 
 
from table2 
 

 
Insert into @temp select Pays,Factory,[Count] from #temp 
 
where Pays='yes' 
 
go

0

首先,如果你有,那么像这样的使用不要使用类似计数的关键字作为一个属性 - > [C 'mount]

DROP TABLE IF EXISTS table1 
 
create table table1 (Pays nvarchar(300)) 
 
DROP TABLE IF EXISTS table2 
 
create table table2 (Factory nvarchar(300), [Count] bigint) 
 

 
/*temp table in sql should be created like this*/ 
 
create table #temp (Pays nvarchar(300),Factory nvarchar(300), [Count] bigint) 
 
/*table variable should be created like this*/ 
 
Declare @temp table (Pays nvarchar (300), Factory nvarchar (300), [Count] bigint) 
 

 

 
insert into #temp(Pays) select Pays 
 
from table1 
 
insert into #temp(Factory,[Count]) select Factory,[Count] 
 
from table2 
 

 
Insert into @temp select Pays,Factory,[Count] from #temp 
 
where Pays='yes' 
 
go

0

我不太清楚你想达到什么目的,但似乎需要从表2数据才能被unpivot操作以能够加入Table 1和Table到另一个。以下就是这个。

declare @t2 table (Factory nvarchar(40), [Count] int, [France] nvarchar(300), [Morocco] nvarchar(300), [USA] nvarchar(300)) 
insert into @t2 values ('SUX',233,'YES','NO','NO') 
, ('DRV',12,'YES','NO','NO') 
, ('HK',144,'YES','NO','NO') 
, ('MA',2016,'NO','YES','NO') 
, ('ZER',2,'NO','YES','NO') 
, ('RST',1777,'NO','YES','NO') 
, ('ZE',24,'NO','NO','YES') 
, ('VR',566,'NO','NO','YES') 

select unpvt.[Pays], unpvt.[Factory], unpvt.[Count], unpvt.[PaysInd] 
from  
    (select [Factory], [count], [France], [Morocco], [USA] 
    from @t2 
    ) p 
unpivot 
    ([PaysInd] for [Pays] IN 
     ([France], [Morocco], [USA]) 
    ) AS unpvt 
join @t1 countries on countries.[Pays] = unpvt.[Pays] and [PaysInd] = 'YES'