2017-05-23 61 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'