First of all: You should avoid STRING_SPLIT()
in almost any case. It does not guarantee to return the items in the expected sort order. This might work in all your tests and break in production with silly hardly to find errors.
There are various answers already, the best one should be the table type parameter. But (if you cannot follow this route), I'd like to suggest two type-safe approaches:
DECLARE @InStr NVARCHAR(MAX) = '0|ABC|3033.9|3032.4444|0|0|0^1|DEF|3033.2577|3033.053|3032.0808|0|0^2|JHI|3032.8376|3033.2596|3033.2259|3033.322|0^3|XYZ|3032.8376|3032.8376|3032.8376|3032.8376|0';
--xml approach (working for almost any version)
--We do the double split in one single action and return a nested XML with <x>
and <y>
elements
--We can fetch the values type-safe from their 1-based position:
SELECT x.value('y[1]','int') AS [First]
,x.value('y[2]','varchar(100)') AS [Second]
,x.value('y[3]','decimal(28,8)') AS Third
,x.value('y[4]','decimal(28,8)') AS Fourth
,x.value('y[5]','decimal(28,8)') AS Fifth
,x.value('y[6]','decimal(28,8)') AS Sixth
,x.value('y[7]','decimal(28,8)') AS Seventh
FROM (VALUES(CAST('<x><y>' + REPLACE(REPLACE(@Instr,'|','</y><y>'),'^','</y></x><x><y>') + '</y></x>' AS XML)))v(Casted)
CROSS APPLY Casted.nodes('/x') b(x);
--json approach (needs v2016+)
--faster than XML
--We transform your string to a JSON-array with one item per row and use another OPENJSON
to retrieve the array's items.
--The WITH
-clause brings in implicit pivoting to retrieve the items type-safe as columns:
SELECT b.*
FROM OPENJSON(CONCAT('[["',REPLACE(@Instr,'^','"],["'),'"]]')) a
CROSS APPLY OPENJSON(CONCAT('[',REPLACE(a.[value],'|','","'),']'))
WITH([First] INT '$[0]'
,[Second] VARCHAR(100) '$[1]'
,[Third] DECIMAL(28,8) '$[2]'
,[Fourth] DECIMAL(28,8) '$[3]'
,[Fifth] DECIMAL(28,8) '$[4]'
,[Sixth] DECIMAL(28,8) '$[5]'
,[Seventh] DECIMAL(28,8) '$[6]') b;
Both approaches return the same result:
+-------+--------+---------------+---------------+---------------+---------------+------------+
| First | Second | Third | Fourth | Fifth | Sixth | Seventh |
+-------+--------+---------------+---------------+---------------+---------------+------------+
| 0 | ABC | 3033.90000000 | 3032.44440000 | 0.00000000 | 0.00000000 | 0.00000000 |
+-------+--------+---------------+---------------+---------------+---------------+------------+
| 1 | DEF | 3033.25770000 | 3033.05300000 | 3032.08080000 | 0.00000000 | 0.00000000 |
+-------+--------+---------------+---------------+---------------+---------------+------------+
| 2 | JHI | 3032.83760000 | 3033.25960000 | 3033.22590000 | 3033.32200000 | 0.00000000 |
+-------+--------+---------------+---------------+---------------+---------------+------------+
| 3 | XYZ | 3032.83760000 | 3032.83760000 | 3032.83760000 | 3032.83760000 | 0.00000000 |
+-------+--------+---------------+---------------+---------------+---------------+------------+