我需要通过分隔符|
拆分字符串,然后对于获得的每个值,我需要在名称字段中插入相同的字符串,如下所示:
INSERT INTO Monitoring (UserId, Name, DateCreated)
VALUES (@UserId, 'abc', getdate())
VALUES (@UserId, 'def', getdate()) etc...
下面是我拆分字符串的代码。
DECLARE @SplitStringTable TABLE (Value nvarchar(MAX) NOT NULL)
DECLARE @StringToSplit nvarchar(MAX) = 'abc|def|gh|ijj'
DECLARE @SplitEndPos int
DECLARE @SplitValue nvarchar(MAX)
DECLARE @SplitDelim nvarchar(1) = '|'
DECLARE @SplitStartPos int = 1
SET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)
WHILE @SplitEndPos > 0
BEGIN
SET @SplitValue = SUBSTRING(@StringToSplit, @SplitStartPos, (@SplitEndPos - @SplitStartPos))
INSERT @SplitStringTable (Value) VALUES (@SplitValue)
SET @SplitStartPos = @SplitEndPos + 1
SET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)
END
BEGIN TRANSACTION T1
DECLARE @i int = 0
WHILE @i < @SplitEndPos
BEGIN
INSERT INTO Monitoring (UserId, Name, DateCreated)
VALUES (@UserId, @Name, getdate())
SET @i = @i + 1
END
COMMIT TRANSACTION T1
请帮忙,我该怎么办?
答案 0 :(得分:2)
那里有很多分割/解析功能。
假设变量:
Declare @UserID int = 1
Declare @String varchar(max)='abc|def'
Insert Into Monitoring (UserId,Name,DateCreated)
Select UserID = @UserID
,Name = Key_Value
,DateCreated = GetDate()
From [dbo].[udf-Str-Parse](@String,'|')
将插入以下内容
UserID Name DateCreated
1 abc 2016-09-26 17:31:24.107
1 def 2016-09-26 17:31:24.107
UDF(如果需要)
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return
(
Select Key_PS = Row_Number() over (Order By (Select null))
,Key_Value = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
修改强>
顺便说一下,如果你只是单独运行解析函数,你会得到以下结果:
Declare @String varchar(max)='abc|def'
Select * From [dbo].[udf-Str-Parse](@String,'|')
-- Returns
Key_PS Key_Value
1 abc
2 def