Home > Database > Mysql Tutorial > 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
Release: 2024-11-21 13:12:10
Original
1035 people have browsed it

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

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

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!

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