I have two tables, TableA
and TableB
.
TableA
has ItemA
as NVARCHAR(MAX)
= "1234,1235,1253,1643,2374". TableB
has ItemB
as INT(MAX)
. What I need is to pass the STRING
from TableA
to TableB
and insert each element into a new row.
Is there a quicker method to do this instead of iterating through the STRING
and comma separating?
I would pass it in as an Array or List but that cannot be done.
Using a CTE, the following should work:
Schema
CREATE TABLE tbl1 (
ItemA nvarchar(max))
INSERT INTO tbl1 VALUES ('1234,1235,1253,1643,2374')
Query
;WITH tmp(Item, ItemA) as (
SELECT LEFT(ItemA, CHARINDEX(',',ItemA+',')-1),
STUFF(ItemA, 1, CHARINDEX(',',ItemA+','), '')
FROM tbl1
UNION ALL
SELECT LEFT(ItemA, CHARINDEX(',',ItemA+',')-1),
STUFF(ItemA, 1, CHARINDEX(',',ItemA+','), '')
FROM tmp
WHERE ItemA > ''
)
INSERT INTO TableB (ItemB) SELECT Item FROM tmp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.