First, the standard answer - don't do this on the server. It's far easier to parse strings on the client.
Second, this isn't as trivial as it appears - this is parsing, not splitting a string. In this case, each token has a different meaning. All string splitting techniques, and the STRING_SPLIT command return a table of unordered tokens.
Third, the splitting technique is one of the slowest, and can't be modified parse instead of split. The fastest techniques are SQLCLR and XML parsing. Both can be modified to return a table with multiple columns.
For example, the following XML parsing function:
CREATE FUNCTION dbo.SplitStrings_XML
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
FROM
(
SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>')
+ '</i>').query('.')
) AS a CROSS APPLY x.nodes('i') AS y(i)
);
GO
works by surrounding each token with i tags, producing <i>OMAHA</i><i>NE</i><i>68117</i>. Then it selects the contents of each I element with tags with CROSS APPLY x.nodes('i')
You can modify it to nest the elements and return the 1st, 2nd and 3rd element, as follows:
CREATE FUNCTION dbo.SplitTriplets_XML
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT
Item1 = o.i.value('@value', 'nvarchar(4000)'),
Item2 = p.i.value('@value', 'nvarchar(4000)'),
Item3 = q.i.value('@value', 'nvarchar(4000)')
FROM
(
SELECT x = CONVERT(XML, '<i value="'
+ REPLACE(@List, @Delimiter, '"><i value="')
+ '"></i></i></i>').query('.')
) AS a
OUTER APPLY x.nodes('/i') AS o(i)
OUTER APPLY x.nodes('/i/i') AS p(i)
OUTER APPLY x.nodes('/i/i/i') AS q(i)
)
In this case, the generated XML is <i value="OMAHA"><i value="NE"><i value="68117" /></i></i> and the OUTER APPLY x.nodes('/i') AS p(i) statements select the root and nested tags as separate tables.
This example :
declare @table table (id int,value nvarchar(200))
insert into @table
values
(1,'OMAHA NE 68117'),
(2,'sdfA Nw 68227')
select id,value,item1 as City,item2 as State,item3 as Zip
from @table x cross apply dbo.SplitTriplets_XML(value,' ')
Returns :
id value City State Zip
----------- ----------------- ------ ------ ------
1 OMAHA NE 68117 OMAHA NE 68117
2 sdfA Nw 68227 sdfA Nw 68227
SELECT @thisvariable=...statement ? How about the standard answer - don't try parsing on the server? Splitting will fail if a name contains spaces