SQL从另一个表插入数据动态列名

时间:2015-11-22 23:47:21

标签: sql sql-server

我试图将数据从一个表插入到另一个表中,动态列名从@array到@ array2

错误

The multi-part identifier "s.id" could not be bound.

SQL CODE:

DECLARE @Array TABLE
(
    id int not null,
    dt varchar(12) not null,
    ld varchar(16) not null,
    val varchar(12) not null,
    ty varchar(4) not null,
    PRIMARY KEY CLUSTERED (id,dt)
)
DECLARE @Array2 TABLE
(
    id int not null,
    dt varchar(12) not null,
    ld varchar(16) not null,
    min varchar(12) null,
    mout varchar(4) null,
    PRIMARY KEY CLUSTERED (id,dt)
)

INSERT INTO @Array VALUES
 ('1','2015-11-11','2015-11-11','20:08','min')
 ,('2','2015-11-11','2015-11-11','20:08','mout')
 ,('3','2015-11-11','2015-11-11','20:08','min')
 ,('4','2015-11-11','2015-11-11','20:08','min')

 Select * from @Array s
 WHERE NOT EXISTS (select s.id,s.dt,s.ld,s.ty from @Array2
    WHERE id != s.id AND dt != s.dt)
    INSERT INTO @Array2 (id,dt,ld,s.ty) VALUES(s.id,s.dt,s.ld,s.val)
                                   ^
                dynamic column name from @Array TABLE

这是SQL Fiddle链接,谢谢。

1 个答案:

答案 0 :(得分:0)

我会按照以下方式重新编写插入内容:

INSERT INTO @Array2 (id,dt,ld,s.ty)
Select s.id,s.dt,s.ld,s.ty from @Array s
left join @Array2 a2 on a2.id = s.id
where a2.id is null

您的错误来自于Array2没有定义ty列的事实。修复它要么放在那里,要么重新评估你投入的内容。此外,小提琴链接竖起大拇指:)

编辑:

在第二次阅读您的问题时,您是否要将该列动态添加到array2?如果是这样,那将需要相当多的捣蛋,我会尝试找到另一种解决方案。像动态那样改变你的架构是不明智的。

EDIT2:

INSERT INTO @Array2 (id,dt,ld,min,mout)
Select 
   s.id,
   s.dt,
   s.ld,
   case s.ty when 'min' then s.val else '' end,
   case s.ty when 'mout' then s.val else '' end
from @Array s
left join @Array2 a2 on a2.id = s.id
where a2.id is null

EDIT3

UPDATE a2
SET 
   a2.dt = s.dt,
   a2.ld = s.ld,
   a2.min = case s.ty when 'min' then s.val else '' end,
   a2.mout = case s.ty when 'mout' then s.val else '' END
FROM @Array2 a2
   LEFT JOIN @Array s ON a2.id = s.id
WHERE s.id IS NOT null