我想在SQL Server表格单元格中插入多个电子邮件,在插入之前我需要检查这些值是否已经存在。
更多说明
Row_id EMAIL_ID
1 abc@xyz.com,abcabc@xyz.com, abc2@xyz.com
2 pqr@xyz.com,pqrabc@xyz.com
现在,如果我插入abcabc@xyz.com,free@xyz.com
,则会显示该值已重复。
我做了这个
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, ',') )
功能
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
它运行正常,但查看100000左右的记录时查询速度很慢
我们可以通过通配符或其他方式做同样的事情吗?
答案 0 :(得分:4)
您可以使用一种技巧来比较以逗号分隔的列表。首先,您需要拆分输入列表。然后,对于每个项目,您需要检查以下内容:
SELECT EMAIL_ID
FROM TR_DEMO
WHERE ','+EMAIL_ID+',' LIKE '%,abcabc@xyz.com,%'
演示:http://www.sqlfiddle.com/#!3/6dd71/2
以下是使用SPLIT
方法生成项目的另一个示例:
SELECT EMAIL_ID
FROM TR_DEMO T
INNER JOIN dbo.split('abcabc@xyz.com,free@xyz.com', ',') s
ON ','+T.EMAIL_ID+',' LIKE '%,'+s.items+',%'
答案 1 :(得分:0)
好的,这个
declare @EmailsToInsert varchar(max) = 'abcabc@xyz.com,free@xyz.com'
declare @insertdata table (email varchar(max))
insert into @insertdata select items from dbo.split(@EmailsToInsert, ',')
-- remove any trailing spaces
update tr_demo
set email_id = replace(email_id, ' ', '')
update t
set email_id = t.email_id + ',' + i.email
from tr_demo t
inner join @insertdata i on ',' + t.email_id + ',' not like '%,' + i.email + ',%'
这是一个使用table var's
的工作示例declare @data table (row_id int, email_id varchar(max))
insert into @data values
(1, 'abc@xyz.com,abcabc@xyz.com, abc2@xyz.com'),
(2, 'pqr@xyz.com,pqrabc@xyz.com')
declare @EmailsToInsert varchar(max) = 'abcabc@xyz.com,free@xyz.com'
declare @insertdata table (email varchar(max))
insert into @insertdata select items from dbo.split(@EmailsToInsert, ',')
update @data
set email_value = replace(email_value, ' ', '')
update t
set email_value = t.email_value + ',' + i.email
from @data t
inner join @insertdata i on ',' + t.email_value + ',' not like '%,' + i.email + ',%'
select * from @data