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!