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 函數的行為,讓您能夠便攜式執行子字串提取任務.
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3