Home  >  Article  >  Database  >  How to achieve the functionality of MySQL's SUBSTRING_INDEX() function in SQL Server?

How to achieve the functionality of MySQL's SUBSTRING_INDEX() function in SQL Server?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 13:12:10930browse

How to achieve the functionality of MySQL's SUBSTRING_INDEX() function in SQL Server?

SQL Server Equivalents of MySQL's SUBSTRING_INDEX Function

MySQL's SUBSTRING_INDEX() function extracts a substring portion before the specified occurrence of a delimiter. To achieve similar functionality in SQL Server, several approaches are available.

T-SQL Scalar Function:

leverages T-SQL and XQuery to break strings into XML rows and extracts rows that match the desired delimiter match.

TSQL Inline Table-Valued Function:

Defines an inline valued table that returns results based on the number of specified delimiter matches, similar to T-SQL Scalar Function but in tabular form.

Usage Example:

T-SQL Scalar Function:

CREATE FUNCTION dbo.SUBSTRING_INDEX
(
    @str NVARCHAR(4000),
    @delim NVARCHAR(1),
    @count INT
)
RETURNS NVARCHAR(4000)
WITH SCHEMABINDING
AS
BEGIN
    /* T-SQL Scalar Function Code */
END;

SELECT dbo.SUBSTRING_INDEX(N'www.somewebsite.com', N'.', 2);

TSQL Inline Table-Valued Function:

CREATE FUNCTION dbo.SUBSTRING_INDEX
(
    @str NVARCHAR(4000),
    @delim NVARCHAR(1),
    @count INT
)
RETURNS TABLE
AS RETURN
    /* TSQL Inline Table-Valued Function Code */

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;

The above is the detailed content of How to achieve the functionality of 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