首页 文章

从两个表中的临时表中动态插入数据

提问于
浏览
-2

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

表格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

谢谢你的帮助 .

4 回答

  • 0

    您希望join (documentation here)运行单个select语句 .

    您可能还想阅读this,因为表变量(@table)和临时表(#table)之间存在重要区别

  • 0

    首先,如果必须,不要使用像Count作为属性的关键字,然后像这样使用 - > [Count]

    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

    首先,如果必须,不要使用像Count作为属性的关键字,然后像这样使用 - > [Count]

    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

    我不太确定你想要实现什么,但似乎你的table2中的数据需要不显示才能将table1和table2连接到另一个 . 以下就是这样做的 .

    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'
    

相关问题