Home:ALL Converter>Address String to Address Fields VIEW or SELECT

Address String to Address Fields VIEW or SELECT

Ask Time:2015-05-28T08:45:25         Author:Lucas Perrett

Json Formatter

I have an address field that is a single line that looks like this:

Dr Robert Ruberry, West End Medical Practice, 38 Russell Street, South Brisbane 4101

I am wanting to write a view that will split that address into Name, Addr1, Addr2, Suburb, Postcode fields for reporting purposes.

I have been trying to USE SUBSTRING and CHARINDEX like this but it doesnt seem to split it correctly.

SUBSTRING([address_Field],CHARINDEX(',',[address_Field]),CHARINDEX(',',[address_Field]))

Can anyone help? TIA

Author:Lucas Perrett,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/30495428/address-string-to-address-fields-view-or-select
mohan111 :

may be this works for your requirement \n\nIF OBJECT_ID('tempdb..#test') IS NOT NULL\n DROP TABLE #test\nCREATE TABLE #test(id int, data varchar(100))\n\nINSERT INTO #test VALUES (1,'Dr Robert Ruberry, West End Medical Practice, 38 Russell Street, South Brisbane 4101')\n\n\nDECLARE @pivot varchar(8000)\nDECLARE @select varchar(8000)\n\nSELECT \n @pivot=coalesce(@pivot+',','')+'[col'+cast(number+1 as varchar(10))+']'\nFROM \n master..spt_values where type='p' and \n number<=(SELECT max(len(data)-len(replace(data,',',''))) FROM #test)\n\nSELECT \n @select='\n select p.col1 As Name,p.col2 as Addr1,p.col3 as Addr3,p.col4 as Postcode\n from (\n select \n id,substring(data, start+2, endPos-Start-2) as token,\n ''col''+cast(row_number() over(partition by id order by start) as varchar(10)) as n\n from (\n select \n id, data, n as start, charindex('','',data,n+2) endPos\n from (select number as n from master..spt_values where type=''p'') num\n cross join \n (\n select \n id, '','' + data +'','' as data \n from \n #test\n ) m\n where n < len(data)-1\n and substring(data,n+1,1) = '','') as data\n ) pvt\n Pivot ( max(token)for n in ('+@pivot+'))p'\n\nEXEC(@select)\n",
2015-05-28T01:48:47
John Hodge :

Here's a couple of options for you. If you're just looking for a quick answer, see this similar question that's already been answered:\n\nT-SQL split string based on delimiter\n\nIf you want some more in depth knowledge of the various options, check this out:\n\nhttp://sqlperformance.com/2012/07/t-sql-queries/split-strings",
2015-05-28T00:56:59
yy