Skip to content

Instantly share code, notes, and snippets.

@dmlogv
Created June 17, 2019 13:24
Show Gist options
  • Save dmlogv/81a4673ccfb0bd2b86f5f11be4462343 to your computer and use it in GitHub Desktop.
Save dmlogv/81a4673ccfb0bd2b86f5f11be4462343 to your computer and use it in GitHub Desktop.
Count substrings
/*
Counts a number of substrings in the given string
Args:
@string
@substring
Returns:
INT
Examples:
select dbo.fncCountSubstrings('бацацацацацацаха', 'ац')
-> 6
*/
CREATE OR ALTER FUNCTION [dbo].[fncCountSubstrings]
(
@string NVARCHAR(max),
@substring NVARCHAR(100)
)
RETURNS INT
AS
BEGIN
IF LEN(@substring) = 0 RETURN 0
DECLARE @result INT = ( LEN(@string) - LEN(REPLACE(@string, @substring, '')) ) / LEN(@substring)
RETURN @result
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment