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
Release: 2024-11-17 09:20:03
Original
976 people have browsed it

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)
Copy after login

For instance:

SELECT SUBSTRING_INDEX('www.somewebsite.com','.',2);
Copy after login

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
Copy after login

Example usage:

SELECT dbo.SUBSTRING_INDEX(N'www.somewebsite.com', N'.', 2) AS Result;
Copy after login

Output:

Result
---------------
www.somewebsite
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template