首先,您可以创建 UDF 以按特定分隔符拆分值(在您的情况下,这是 SPACE):
CREATE FUNCTION [dbo].[Split](@String nvarchar(4000), @Delimiter char(1))
returns @temptable TABLE (rownumber INT , items nvarchar(4000))
as
begin
declare @idx int
declare @slice nvarchar(4000)
DECLARE @rownumber int = 1
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(rownumber, Items) values(@rownumber, @slice)
set @String = right(@String,len(@String) - @idx)
SET @rownumber = @rownumber + 1
if len(@String) = 0 break
end
return
end
GO
之后,编写简单的INSERT INTO SELECT...
查询就足够了:
INSERT INTO dbo.Table_2
( column1, column2 )
SELECT
item1.items ,
item2.items
FROM dbo.Split((SELECT column1 FROM dbo.Table_1), SPACE(1)) AS item1
FULL JOIN dbo.Split((SELECT column2 FROM dbo.Table_1), SPACE(1)) AS item2
ON item1.rownumber = item2.rownumber
Table_1
是实际值所在Table_2
的表,是最终行的表。
SQL 小提琴演示