一次将两个逗号分割字段作为行插入临时表

时间:2017-12-05 09:56:30

标签: sql sql-server tsql

我试图一次将两个变量插入到同一个临时表中,但是面临语法错误。

使用的SQL Server版本是2012年。非常感谢任何可能的实现方法。 我更喜欢Azure和Server 2012的支持。

消息来源:

VARCHAR(MAX) ProgramName  AS 'SP1, SP2, SP3'
INT ProgramId AS 12,13,14
Id = Identity Column (TO be auto generated with init as 1 and seed as 1)

期望的输出:

Id ---- ProgramName  --- ProgramId

1  ------ SP1   ---------  12

2 ------- SP2   ---------  13

3 ------- SP3   ---------- 14

TRIED CODE:

IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL 
DROP TABLE #tempTable;

CREATE TABLE #tempTable (
Id          INT IDENTITY(1,1),
ProgramName VARCHAR(50) NULL,
ProgramId   INT  NULL);

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @InsertStatement varchar(max) = 'insert into 
#tempTable(ProgramName,ProgramId) 
        values ('+REPLACE(@string,',',','+REPLACE(@new,',','),(')+',(')++')';
PRINT(@InsertStatement)
EXECUTE (@InsertStatement);

SELECT * FROM #tempTable;

2 个答案:

答案 0 :(得分:1)

我想使用xml节点方法来分割您的数据&将它们插入temp

;with cte as
(
    select 
          row_number() over (order by (select 1)) [rn],
          s.value('.', 'varchar(max)') [string] from
    (
       select cast('<m>'+replace(@string, ',', '</m><m>')+'</m>' as xml) [string]
    ) as a cross apply string.nodes ('/m') as string(s)
), cte1 as
(
    select 
          row_number() over (order by (select 1)) [rn],
          s.value('.', 'varchar(max)') new from
    (
       select cast('<m>'+replace(@new, ',', '</m><m>')+'</m>' as xml) [new]
    ) as a cross apply new.nodes ('/m') as string(s)
)

insert into #tempTable
select c.string, c1.new from cte c
join cte1 c1 on c1.rn = c.rn

结果:

Id  ProgramName ProgramId
1   aa         1
2   dd         17
3   fe         25
4   grt        44
5   rge        46
6   lk         67
7   se         88

答案 1 :(得分:1)

试试这个

IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL 
DROP TABLE #tempTable;

CREATE TABLE #tempTable 
(
    Id          INT IDENTITY(1,1),
    ProgramName VARCHAR(50) NULL,
    ProgramId   INT  NULL
);

declare @t as table
(
    seqno int identity(1,1),
    ProgramId   INT  NULL
)

DECLARE @string varchar(max) = 'aa,dd,fe,grt,rge,lk,se';
DECLARE @new varchar(max) = '1,17,25,44,46,67,88';

DECLARE @sql1 varchar(max) = 'SELECT '''+REPLACE(@string,',',''' UNION ALL SELECT ''')+''''
DECLARE @sql2 varchar(max) = 'SELECT '''+REPLACE(@new,',',''' UNION ALL SELECT ''')+''''

PRINT(@sql1)
PRINT(@sql2)

insert into #tempTable(ProgramName)
exec(@sql1)

insert into @t(ProgramId)
exec(@sql2)

update a
set 
ProgramId = b.ProgramId
from #tempTable a
inner join @t b
on a.Id = b.seqno

SELECT * FROM #tempTable;