Home >Database >Mysql Tutorial >How to Replicate MySQL's SUBSTRING_INDEX Function in SQL Server?
When migrating queries from MySQL to SQL Server, it's often necessary to find SQL Server equivalents for commonly used MySQL functions.
MySQL's SUBSTRING_INDEX() function retrieves a substring from a given string based on the occurrence of a specified delimiter. Its syntax is:
SUBSTRING_INDEX(str, delim, count)
For instance:
SELECT SUBSTRING_INDEX('www.somewebsite.com','.',2);
This would return 'www.somewebsite'.
One viable option in T-SQL for replicating SUBSTRING_INDEX()'s functionality is a combination of XQuery and a scalar function:
CREATE FUNCTION dbo.SUBSTRING_INDEX ( @str NVARCHAR(4000), @delim NVARCHAR(1), @count INT ) RETURNS NVARCHAR(4000) WITH SCHEMABINDING BEGIN DECLARE @XmlSourceString XML; SET @XmlSourceString = (SELECT N'<root><row>' + REPLACE( (SELECT @str AS '*' FOR XML PATH('')) , @delim, N'</row><row>' ) + N'</row></root>'); 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;
Output:
Result --------------- www.somewebsite
The above is the detailed content of How to Replicate MySQL's SUBSTRING_INDEX Function in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!