Reputation: 93
I have this question for you.I am working a function which has the whole address in one field.I am trying to separate it.I have started working on the one below and I am having difficulty when I try to work on the zip ,I want to test if there is a zip first at the end and if so I am trying to separate it from the state.Could you please have alook at it?Thanks alot guys as usual I appreciate you support..
declare @var1 varchar(100)='1234 S.Almeda way,Seattle,WA9810'--just an example
,@u int
,@r int
,@var2 varchar(100)
,@var3 varchar(100)
,@Zip varchar(25)
,@var4 varchar(100)=null
set @u = charindex(',', @var1)
set @var2=rtrim(ltrim(substring(@var1, @u+1, 999)))
set @r=CHARINDEX(',',@var2)
set @var3=rtrim(ltrim(substring(@var2, @r+1, 999)))
--set @var4=RIGHT(@var3,5)--not enough
if (len(@var3)>=5 and ISNUMERIC(@var3)=1 )
set @var4=RIGHT(@var3,5)
set rtrim(substring(@var3,1,len(@var3)-5))
else set @var4=''
Upvotes: 1
Views: 69
Reputation: 107716
Here's some sample code you can merge into yours
declare @var1 varchar(100)='1234 S.Almeda way,Seattle,WA9810'--just an example
declare @lastcomma int = len(@var1) - charindex(',', reverse(@var1)+',')
declare @lastPart varchar(100) = substring(@var1, @lastcomma+2, 100)
select @lastPart
declare @zipstart int = patindex('%[0-9]%', @lastpart)
declare @zip varchar(5) = ''
if @zipstart > 0
select @zip = substring(@lastpart, @zipstart, 5), @lastPart = rtrim(substring(@lastpart,1,@zipstart-1))
select @lastpart, @zip
Upvotes: 1
Reputation: 7214
You are obvioulsy looking for a split function, which is not built-in SQL Server.
I've stop reading your code when I saw the name you give to your variables (really bad choices, it should have some kind of meaning)
There are many ways to implement it, I'll pick one randomly from a google search (nah, I'm not ashamed, I don't want to reinvent the wheel)
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(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
use it this way :
select top 10 * from dbo.split('1234 S.Almeda way,Seattle,WA9810',',')
It'll give you a column with a result in each row
You'll find plenty of other example with a quick web search. ;)
Upvotes: 0