SQL server tokenizer
SQL Server中是否有方法创建一个函数,使以下字符串"abc,def,ghi"输出值3。
然后,是否可以使用一个函数来指定要输出的字符串的标记。所以输入将是您想要返回的字符串和标记。输入:('abc,def,ghi',2)输出:DEF
这比您正在编写的代码短得多:
简短的解释:用
XML易于索引。必须使用xquery函数
1 2 3 4 5 6 7 8 9 | DECLARE @string VARCHAR(MAX)='ABC,DEF,GHI'; DECLARE @INDEX INT=2; WITH AsXML AS ( SELECT CAST('<x>' + REPLACE(@string,',','</x><x>') + '</x>' AS XML) AS Splitted ) SELECT Splitted.value('/x[sql:variable("@index")][1]','varchar(max)') FROM AsXML |
编辑:在这里,您可以找到一个完整工作的例子,将此方法作为函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | CREATE FUNCTION dbo.Tokenizer ( @string VARCHAR(MAX) ,@INDEX INT ) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @RetVal VARCHAR(MAX); WITH AsXML AS ( SELECT CAST('<x>' + REPLACE(@string,',','</x><x>') + '</x>' AS XML) AS Splitted ) SELECT @RetVal = Splitted.value('/x[sql:variable("@index")][1]','varchar(max)') FROM AsXML; RETURN @RetVal; END GO SELECT dbo.Tokenizer( 'ABC,DEF,GHI',2); --Returns"DEF" GO --Clean up DROP FUNCTION dbo.Tokenizer; |
第一个问题
1 2 3 4 | DECLARE @token VARCHAR(20) SET @token = 'ABC,DEF,GHI' SELECT len(@token) - len(REPLACE(@token ,',','')) + 1 |
此函数执行第2部分所需的操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | CREATE FUNCTION dbo.itemAtIndexInASplitString( @stringToSplit VARCHAR(MAX), @delimiter VARCHAR(5), @indexToReturn INT) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @returnList TABLE ([ID] INT, [Name] [nvarchar] (500)) DECLARE @name NVARCHAR(255) DECLARE @pos INT DECLARE @INDEX INT DECLARE @return_value VARCHAR(MAX) SET @INDEX = 0 SET @return_value = NULL WHILE CHARINDEX(@delimiter, @stringToSplit) > 0 BEGIN SELECT @pos = CHARINDEX(@delimiter, @stringToSplit) SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1) INSERT INTO @returnList SELECT @INDEX, @name SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos) SET @INDEX = @INDEX + 1 END INSERT INTO @returnList SELECT @INDEX, @stringToSplit SELECT @return_value = Name FROM @returnList WHERE [ID] = @indexToReturn RETURN @return_value END GO |