我有一个像这样的字符串:
72594206916,2,1/2/08,Tacoma,WA:72594221856,5,5/7/13,San Francisco,CA:72594221871,99,12/30/12,Dallas,TX
Run Code Online (Sandbox Code Playgroud)
这基本上是3行中的5个值(来自ASP.NET网格).我需要将此字符串拆分为SQL Server表中的5列和3行.各个值用逗号分隔,冒号用行分隔.
我发现了一个将字符串拆分成片段的函数,我可以从这个字符串中获取行:
declare @testString varchar(100)
set @testString = '72594206916,2,1/2/08,Tacoma,WA:72594221856,5,5/7/13,San Francisco,CA:72594221871,99,12/30/12,Dallas,TX'
select *
from dbo.SplitString(@testString, ':')
Run Code Online (Sandbox Code Playgroud)
给我:
72594206916,2,1/2/08,Tacoma,WA
72594221856,5,5/7/13,San Francisco,CA
72594221871,99,12/30/12,Dallas,TX
Run Code Online (Sandbox Code Playgroud)
这给了我一个带有三行的结果集(函数输出一个表).我可以同时再次调用此函数并以某种方式将其输出插入表中吗?
t-c*_*.dk 12
假设您的拆分返回列名称项
insert <table> (colname)
select y.item
from dbo.SplitString(@testString, ':') x
cross apply
dbo.SplitString(x.item, ',') y
Run Code Online (Sandbox Code Playgroud)
小智 5
创建此 SQL 函数:
CREATE FUNCTION [dbo].[StringSplit](@input NVARCHAR(MAX), @delimiter CHAR(1)=',')
RETURNS @returnTable TABLE(item NVARCHAR(100)) AS
BEGIN
IF @input IS NULL RETURN;
DECLARE @currentStartIndex INT, @currentEndIndex INT,@length INT;
SET @length=LEN(@input);
SET @currentStartIndex=1;
SET @currentEndIndex=CHARINDEX(@delimiter,@input,@currentStartIndex);
WHILE (@currentEndIndex<>0)
BEGIN
INSERT INTO @returnTable VALUES (LTRIM(SUBSTRING(@input, @currentStartIndex, @currentEndIndex-@currentStartIndex)))
SET @currentStartIndex=@currentEndIndex+1;
SET @currentEndIndex=CHARINDEX(@delimiter,@input,@currentStartIndex);
END
IF (@currentStartIndex <= @length)
INSERT INTO @returnTable
VALUES (LTRIM(SUBSTRING(@input, @currentStartIndex, @length-@currentStartIndex+1)));
RETURN;
END;
Run Code Online (Sandbox Code Playgroud)
使用示例:
DECLARE @testString VARCHAR(100)
SET @testString = '72594206916,2,1/2/08,Tacoma,WA:72594221856,5,5/7/13,San Francisco,CA:72594221871,99,12/30/12,Dallas,TX'
SELECT *
FROM [dbo].[StringSplit](@testString, DEFAULT)
Run Code Online (Sandbox Code Playgroud)
结果(表):
72594206916
2
1/2/08
Tacoma
WA:72594221856
5
5/7/13
San Francisco
CA:72594221871
99
12/30/12
Dallas
Run Code Online (Sandbox Code Playgroud)