Friday, January 17, 2014

turn any list of text into a table

If you're like me and you regularly get people emailing you long lists of .. whatever.. zip codes, addresses, VIN numbers, etc .. and they want you to do something with each item in the list, but the lists are always inconsistent and you spend a lot of time just cleaning up the list so you can move forward with the task, here's a handy quick cleaner upper I made. it will turn this:
lkfdjhhdf 2356345 dfsdsf dfds df fd dsffd sad,dsa,,DS,F,,FSADFSDF, DF
into a nice table:
first of all, you need this function. Split parameter string from comma seperator in SQL IN clause then we do this:
DECLARE @item_list VARCHAR(4000)
SET @item_list = 
'
lkfdjhhdf
2356345

dfsdsf

dfds

df
fd

dsffd
sad,dsa,,DS,F,,FSADFSDF,
DF
'

DECLARE @c VARCHAR(4000) = REPLACE(REPLACE(REPLACE(REPLACE(@item_list,CHAR(13)+CHAR(10),','),',,',','),',,',','),',,',',')
IF RIGHT(@c,1) = ',' SET @c = LEFT(@c,LEN(@c)-1)
IF LEFT(@c,1) = ',' SET @c = RIGHT(@c,LEN(@c)-1)

IF RIGHT(@c,1) = ',' SET @c = LEFT(@c,LEN(@c)-1)
IF LEFT(@c,1) = ',' SET @c = RIGHT(@c,LEN(@c)-1)

set nocount on
DECLARE @list AS TABLE (item VARCHAR(100))

INSERT @list
SELECT [sID] FROM redbumperdb.dbo.UF_CSVToTable(@c)

SELECT * FROM @list AS l

No comments: