当前位置: 代码迷 >> Sql Server >> 一次从一条记录获取多个值插入的有关问题
  详细解决方案

一次从一条记录获取多个值插入的有关问题

热度:394   发布时间:2016-04-27 22:00:08.0
一次从一条记录获取多个值插入的问题
表A
uaserid uaserid1 uaserid2 uaserid3  
  1 3 4 5

表B为空表,如何获得表A的数据插入表B,最终结果是
id
3
4
5



------解决方案--------------------
SQL code
insert into b(id)select uaserid from Aunion allselect uaserid1 from Aunion allselect uaserid2 from Aunion allselect uaserid3 from A
------解决方案--------------------
SQL code
if object_id('A') is not null drop table A goselect 1 as uaserid,3 as uaserid1,4 as uaserid2,5 as uaserid3 into Aif object_id('B') is not null drop table B goselect a.uaserid1 as ID into Bfrom (select uaserid1 from A union all      select uaserid2 from A union all      select uaserid3 from A) aselect * from B
------解决方案--------------------
SQL code
insert into b(id)select uaserid1 from Aunion allselect uaserid2 from Aunion allselect uaserid3 from A
------解决方案--------------------
SQL code
create function [dbo].[m_split](@c varchar(2000),@split varchar(2))     returns @t table(col varchar(200))     as       begin         while(charindex(@split,@c)<>0)           begin             insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))               set @c = stuff(@c,1,charindex(@split,@c),'')           end         insert @t(col) values (@c)         return   endgo[email protected],@表Bdeclare @表A table (uaserid int,uaserid1 nvarchar(20),uaserid2 nvarchar(20),uaserid3 nvarchar(20))insert into @表Aselect 1,3,4,5declare @表B table (id int)declare @t varchar(20)select @t= uaserid1+','+uaserid2+','+uaserid3 from @表A--插入数据insert into @表Bselect * from dbo.m_split(@t,',')--查询结果select * from @表B/*id-----------345*/
  相关解决方案