I have a column in a sql server table named [City_St_Zip] that contains records that look like this
Dallas, TX 12345
What I would like to do is separate the column into three different columns (i.e. City, State and Zip) like this:
Dallas
TX
12345
I am not sure how to go about this in SQL
I have tried the following
DECLARE @X NVARCHAR(100),
DECLARE @T NVARCHAR(100),
SELECT
@X = [City_St_Zip],
@T = [NewDivision]
FROM
dbo.Invoice
CROSS APPLY STRING_SPLIT(@X, ',');
This yielded 0 results so I am pretty sure I did that incorrectly
Any suggestions? I am using SQL Server 2019
EDIT: I also tried this which is closer to what I want
SELECT
value
FROM
dbo.Invoice
CROSS APPLY STRING_SPLIT([City_St_Zip], ',');
That gives me a result set of:
Dallas
TX 12345
So I guess this is convoluted and needs both a comma and a space delimiter. Would I just put the value through another STRING_SPLIT?
STRING_SPLITas the delimiter, and yet in your example, you seem to want to split by a space. Also, why not pass[City_St_Zip]to the function instead of@X? Also, you should consider how to handle cities that have more than one word in the name if you indeed want to split by a space.valueoutput fromstring_splitwhich is going to benullin this case because you're trying to split@xinstead of yourCity_St_Zipcolumn. See the String_Split docs, https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql