Tuesday, May 16, 2017

Splitting Text field to columns in SQL

We sometimes have to split a text field into columns, if the requirement is to split in 4 columns we can use below logic:

SELECT [name]
,[dish]
,[sides]
,[drinks]
,[dessert]
,[comments]
FROM [Database].[dbo].TABLE





SELECT NAME
,PARSENAME(REPLACE(dish, ' or ', '.'), 2) dish1
,PARSENAME(REPLACE(dish, ' or ', '.'), 1) dish2
,[sides]
,[drinks]
,[dessert]
FROM [Database].[dbo].TABLE







If your text field has delimiter in form of and or a comma, just replace it in place of or and it should work! The only issue is, it can only divide four columns. 

Hope it helps :)










No comments:

Post a Comment