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中文網其他相關文章!