You can split and join as below:
;with cte_vids as (
select * from #tblmove
cross apply udf_split( vehicleids, ',')
), cte_vtypes as (
select * from #tblmove
cross apply udf_split( vehicletypes, ',')
)
select cid.movementid, cid.[value] as vehichleid, cty.[value] as vehicletype,
case when cid.rown = 1 then cid.total else null end as total
from cte_vids cid join cte_vtypes cty
on cid.movementid = cty.movementid and cid.vehicleids = cty.vehicleids and cid.rown = cty.rown
Answers as below:
+------------+------------+-------------+-------+
| movementid | vehichleid | vehicletype | total |
+------------+------------+-------------+-------+
| 1 | V01 | F | 200 |
| 1 | V02 | T | NULL |
| 2 | V04 | V | 140 |
| 3 | V03 | F | 300 |
| 3 | V02 | F | NULL |
+------------+------------+-------------+-------+
I used a function which you can create as below:
CREATE Function dbo.udf_split( @str varchar(max), @delimiter as varchar(5) )
RETURNS @retTable Table
( RowN int,
value varchar(max)
)
AS
BEGIN
DECLARE @xml as xml
SET @xml = cast(('<X>'+replace(@str,@delimiter ,'</X><X>')+'</X>') as xml)
INSERT INTO @retTable
SELECT RowN = Row_Number() over (order by (SELECT NULL)), N.value('.', 'varchar(MAX)') as value FROM @xml.nodes('X') as T(N)
RETURN
END