MySQL 中 substring_index 函数的 SQL Server 等效项
MySQL 中的 substring_index 函数用于从给定字符串之前的指定字符串中提取子字符串分隔符出现的次数。要在 SQL Server 2012 中实现类似的功能,您可以采用以下方法之一:
T-SQL 标量函数:
CREATE FUNCTION dbo.SUBSTRING_INDEX ( @str NVARCHAR(4000), @delim NVARCHAR(1), @count INT ) RETURNS NVARCHAR(4000) WITH SCHEMABINDING BEGIN -- Convert the string to an XML document for processing DECLARE @XmlSourceString XML; SET @XmlSourceString = (SELECT N'<root><row>' + REPLACE( (SELECT @str AS '*' FOR XML PATH('')) , @delim, N'</row><row>' ) + N'</row></root>'); -- Extract the desired substring using XQuery RETURN STUFF ( (( SELECT @delim + x.XmlCol.value(N'(text())[1]', N'NVARCHAR(4000)') AS '*' FROM @XmlSourceString.nodes(N'(root/row)[position() <= sql:variable("@count")]') x(XmlCol) FOR XML PATH(N''), TYPE ).value(N'.', N'NVARCHAR(4000)')), 1, 1, N'' ); END GO -- Example usage SELECT dbo.SUBSTRING_INDEX(N'www.somewebsite.com', N'.', 2) AS Result;
T- SQL 内联表值函数:
CREATE FUNCTION dbo.SUBSTRING_INDEX ( @str NVARCHAR(4000), @delim NVARCHAR(1), @count INT ) RETURNS TABLE AS RETURN WITH Base AS ( SELECT XmlSourceString = CONVERT(XML, (SELECT N'<root><row>' + REPLACE( (SELECT @str AS '*' FOR XML PATH('')) , @delim, N'</row><row>' ) + N'</row></root>')) ) SELECT STUFF ( (( SELECT @delim + x.XmlCol.value(N'(text())[1]', N'NVARCHAR(4000)') AS '*' FROM Base b CROSS APPLY b.XmlSourceString.nodes(N'(root/row)[position() <= sql:variable("@count")]') x(XmlCol) FOR XML PATH(N''), TYPE ).value(N'.', N'NVARCHAR(4000)')), 1, 1, N'' ) AS Result; GO -- Example usage SELECT * FROM ( SELECT N'www.somewebsite.com' UNION ALL SELECT N'www.yahoo.com' UNION ALL SELECT N'www.outlook.com' ) a(Value) CROSS APPLY dbo.SUBSTRING_INDEX(a.Value, N'.', 2) b;
这些函数允许您复制 SQL Server 中 MySQL substring_index 函数的行为,使您能够便携式地执行子字符串提取任务。
以上是如何在SQL Server 2012中实现MySQL的SUBSTRING_INDEX功能?的详细内容。更多信息请关注PHP中文网其他相关文章!