拆分多列并存储到临时 table
Split multiple column and store into temp table
我有样本数据:
Table: tblsampledata
create table tblsampledata
(
column1 varchar(50),
column2 varchar(50)
);
insert into tblsampledata values('Bob Frapples','Gail Forcewind');
insert into tblsampledata values('Paul Molive','Mario Speedwagon');
并且我有列映射 table 与 table 名称:
Table:tblmapping
create table tblmapping
(
tblname varchar(100),
columnmap varchar(max)
);
insert into tblmapping values('tblsampledata','[column1]|[column2]');
注意:我想拆分存在于tblmapping
of table name in column tblname
中的列数据并存储它进入温度 table.
预期结果:#TempTable
column1 column2
---------------------
Bob Gail
Frapples Forcewind
Paul Mario
Molive Speedwagon
您需要使用动态查询来实现。
您可以像下面这样尝试。
select @xml = Cast(( '<X>' + Replace(columnmap, '|', '</X><X>') + '</X>' ) AS XML)
from tblmapping where tblname =@tablename
DECLARE @query AS NVARCHAR(max) = 'select ' + Stuff((SELECT DISTINCT ', ' + value
FROM (
SELECT n.value('.', 'varchar(100)') AS value
FROM @xml.nodes('X') AS T(n)
)t
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
+ ' from ' + @tablename;
exec sp_executesql @query
要拆分第 1 列和第 2 列,您可以使用如下查询。
SELECT CASE
WHEN n = 1 THEN LEFT(column1, Charindex(' ', column1) - 1)
WHEN n = 2 THEN RIGHT(column1, Charindex(' ', Reverse(column1)) - 1)
END AS column1,
CASE
WHEN n = 1 THEN LEFT(column2, Charindex(' ', column2) - 1)
WHEN n = 2 THEN RIGHT(column2, Charindex(' ', Reverse(column2)) - 1)
END AS column2
FROM tblsampledata t1
CROSS JOIN ( VALUES(1),(2) )t(n)
Full Demo 使用动态查询
我有样本数据:
Table: tblsampledata
create table tblsampledata
(
column1 varchar(50),
column2 varchar(50)
);
insert into tblsampledata values('Bob Frapples','Gail Forcewind');
insert into tblsampledata values('Paul Molive','Mario Speedwagon');
并且我有列映射 table 与 table 名称:
Table:tblmapping
create table tblmapping
(
tblname varchar(100),
columnmap varchar(max)
);
insert into tblmapping values('tblsampledata','[column1]|[column2]');
注意:我想拆分存在于tblmapping
of table name in column tblname
中的列数据并存储它进入温度 table.
预期结果:#TempTable
column1 column2
---------------------
Bob Gail
Frapples Forcewind
Paul Mario
Molive Speedwagon
您需要使用动态查询来实现。
您可以像下面这样尝试。
select @xml = Cast(( '<X>' + Replace(columnmap, '|', '</X><X>') + '</X>' ) AS XML)
from tblmapping where tblname =@tablename
DECLARE @query AS NVARCHAR(max) = 'select ' + Stuff((SELECT DISTINCT ', ' + value
FROM (
SELECT n.value('.', 'varchar(100)') AS value
FROM @xml.nodes('X') AS T(n)
)t
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
+ ' from ' + @tablename;
exec sp_executesql @query
要拆分第 1 列和第 2 列,您可以使用如下查询。
SELECT CASE
WHEN n = 1 THEN LEFT(column1, Charindex(' ', column1) - 1)
WHEN n = 2 THEN RIGHT(column1, Charindex(' ', Reverse(column1)) - 1)
END AS column1,
CASE
WHEN n = 1 THEN LEFT(column2, Charindex(' ', column2) - 1)
WHEN n = 2 THEN RIGHT(column2, Charindex(' ', Reverse(column2)) - 1)
END AS column2
FROM tblsampledata t1
CROSS JOIN ( VALUES(1),(2) )t(n)
Full Demo 使用动态查询