我不提倡在 SQL Server 中使用这种编程风格,但这就是我将如何做你要求做的事情。首先,将字符串标记为表变量中的单个单词。然后在表变量上打开一个光标并循环遍历单词,break
如果我们从 dbo.countries 中找到结果则调用。请注意,循环在 SQL Server 中非常低效。UDF 表函数来自这里:How to split a string in T-SQL?
-- Create the UDF
CREATE FUNCTION Splitfn(@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(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
go
-- Create the dbo.countries table so we can test our code later
create table dbo.countries (code char(2), name varchar(100))
go
-- Insert one record in dbo.countries so we can test our code later
insert into dbo.countries (code, name)
select 'PH', 'PHILIPPINES'
go
-- for one @String input, this is what I would do
declare @String varchar(1000) = '12345 MY SUPER LONG ADDRESS IN THE PHILIPPINES'
declare @CountryCode char(2) = ''
declare @done bit = 0x0
declare @word varchar(1000)
declare @words table (word varchar(250) primary key)
-- Break apart your @String into a table of records, only returning the DISTINCT values.
-- Join on the domain list so we can only process the ones that will return data in the CURSOR (eliminating excess looping)
insert into @words (word)
--
select distinct items as word
from dbo.Splitfn(@String, ' ') s
join dbo.countries c
on lower(c.name) = lower(s.items)
declare word_cursor CURSOR for
select word
from @words w
open word_cursor
fetch next from word_cursor into @word
while @@FETCH_STATUS = 0
begin
select @CountryCode = code
from dbo.countries
where name = @word
if @@trancount > 0
begin
break
end
fetch next from word_cursor into @word
end
-- clean up the cursor
close word_cursor
deallocate word_cursor
-- return the found CountryCode
select @CountryCode