I am trying to get rows from the table Mails if the column [To] has the mail abc@mail.
The simple solution would be Select * from Mails where [To] = 'abc@mail'
But the thing is [To] column has data like 123@mail;abc@mail;aabc@mail etc separated by semicolons where To is multiple emails sent
I know I could do something like Select * from Mails where [To] like '%abc@mail%'
but that won't solve the problem if the given mail is a substring of another mail. I thought of a split string solution
I have a split_string function like this,
CREATE FUNCTION [dbo].[split_string]
(
@string_value NVARCHAR(MAX),
@delimiter_character CHAR(1)
)
RETURNS @result_set TABLE(splited_data NVARCHAR(MAX)
)
BEGIN
DECLARE @start_position INT,
@ending_position INT
SELECT @start_position = 1,
@ending_position = CHARINDEX(@delimiter_character, @string_value)
WHILE @start_position < LEN(@string_value) + 1
BEGIN
IF @ending_position = 0
SET @ending_position = LEN(@string_value) + 1
INSERT INTO @result_set (splited_data)
VALUES(SUBSTRING(@string_value, @start_position, @ending_position - @start_position))
SET @start_position = @ending_position + 1
SET @ending_position = CHARINDEX(@delimiter_character, @string_value, @start_position)
END
RETURN
END
which would return splitted string of a single data in a column and the function is working fine.
I tried executing the query
Select *
from Mails
where 'abc@mail' in (
Select *
from dbo.split_string((SELECT [To] FROM Mails) , ';')
)
which is throwing the error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
I need help proceeding from here. I am using Microsoft SQL Server 2014.
WHILE
loops also perform very poorly. I strongly suggest that if you need to use a user defined function you make an inline table value function with a set based solution; it will significantly more performant.DelimitedSplit8K_LEAD
/DelimitedSplitN4k_LEAD
).