Home >Database >Mysql Tutorial >How to Replicate MySQL's SUBSTRING_INDEX Function in SQL Server?

How to Replicate MySQL's SUBSTRING_INDEX Function in SQL Server?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 09:20:03975browse

How to Replicate MySQL's SUBSTRING_INDEX Function in SQL Server?

SQL Server equivalent of the MySQL substring_index function

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

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'.

Equivalent in SQL Server T-SQL

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn