I want to insert multiple email into SQL Server table cell and before inserting them I need check whether the values are already there or not.
For more clarification
Row_id EMAIL_ID
1 abc@xyz.com,abcabc@xyz.com, abc2@xyz.com
2 pqr@xyz.com,pqrabc@xyz.com
Now If I insert abcabc@xyz.com,free@xyz.com, it will show that value is duplicated.
I did this
select EMAIL_ID
from TR_DEMO
INNER JOIN dbo.split('abcabc@xyz.com,free@xyz.com', ',') s
ON s.items IN (select items from dbo.split(EMAIL_ID, ',') )
Function
CREATE FUNCTION [dbo].[Split]
(
@String varchar(8000),
@Delimiter char(1)
)
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(rtrim(ltrim(@slice)))
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
It works fine, but query is slow while checking the records around 100000
Can we do the same by wildcard or something else?
There is a trick you can use for comparing against a comma-separated list. First, you’ll want to split your input list. Then for each item, you’ll want to check the following:
Demo: http://www.sqlfiddle.com/#!3/6dd71/2
Here’s another example using your
SPLITmethod to generate the items:http://www.sqlfiddle.com/#!3/a9a7b/1