TRUNCATE TABLE LocationWithSourceId
;WITH roy AS
(
SELECT LocationID,
SourceLocationID = CAST(
LEFT(
SourceLocationID,
CHARINDEX(',', SourceLocationID + ',') -1
) AS
NVARCHAR(100)
),
SPLIT = CAST(
STUFF(
SourceLocationID + ',',
1,
CHARINDEX(',', SourceLocationID + ','),
''
)
AS NVARCHAR(100)
)
FROM (
SELECT LocationID,
SourceLocationID
FROM sf_Locations
WHERE SourceLocationID LIKE '%,%'
) k
UNION ALL
SELECT LocationID,
SourceLocationID = CAST(LEFT(SPLIT, CHARINDEX(',', SPLIT) -1) AS NVARCHAR(100)),
SPLIT = CAST(
STUFF(SPLIT, 1, CHARINDEX(',', SPLIT), '') AS NVARCHAR(100)
)
FROM Roy
WHERE SPLIT > ''
)
--SELECT * FROM roy
INSERT LocationWithSourceId
SELECT x.LocationID,
x.SourceLocationID
FROM roy x
UNION ALL
SELECT LocationID,
SourceLocationID
FROM sf_Locations
WHERE SourceLocationID NOT LIKE '%,%' AND SourceLocationID <> ''