我有一个字符串:
@TempCol = sigma_x1,sigma_x2,...,sigma_xd,XX,YY,ZZ
我想获得一个子字符串来获取字符串sigma_x1,sigma_x2,...,sigma_xd
。
d
是一个变量,因此它可以是1,3,20,......等。
我知道d的值,但我不知道如何用d
项来获取原始字符串的子字符串。
我试过了:
@L = ''
SET @ColumnNo = 0
WHILE @ColumnNo <= @d
BEGIN
SET @L = @L + ' ' + SUBSTRING(@TempCol, 1, CHARINDEX(',',@TempCol)-1 )
SET @TempCol = REPLACE ( @TempCol, LTRIM(RTRIM(@L) ) ,'')
Set @ColumnNo = @ColumnNo + 1
PRINT @L
END
但我不知道如何获得预期的结果。
答案 0 :(得分:1)
您需要的是分割功能(如下图所示)。
With SplitItems As
(
Select Position, Value
, Row_Number() Over ( Order By Position ) As ItemNum
From dbo.udf_Split( @TempCol, ',' )
)
Select Value
From SplitItems
Where ItemNum <= @d
如果您希望组装的字符串达到给定点,您只需执行以下操作:
With SplitItems As
(
Select Position, Value
, Row_Number() Over ( Order By Position ) As ItemNum
From dbo.udf_Split( @TempCol, ',' )
)
Select ',' + Value
From SplitItems
Where ItemNum <= @d
Order By ItemNum
For Xml Path('')
分割功能:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION [dbo].[udf_Split]
(
@DelimitedList nvarchar(max)
, @Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, Len(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List) / 2
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
答案 1 :(得分:1)
DECLARE @TempCol varchar(max), @d int, @p int, @Result varchar(max);
SET @TempCol = 'item1,item2,itemA,itemB,item#,item$';
SET @d = 3;
SET @p = 1;
WHILE @d > 0 AND @p > 0 BEGIN
SET @p = CHARINDEX(',', @TempCol, @p);
IF @p > 0 SET @p = @p + 1;
SET @d = @d - 1;
END;
IF @p = 0
SET @Result = @TempCol
ELSE
SET @Result = SUBSTRING(@TempCol, 1, @p - 2);
SELECT @Result;
基本上,循环只搜索要切入的最终位置。在循环之后提取子字符串。
如果您指定的@d
太大,则结果只会是@TempCol
,否则您将获得所需的项目数。