Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Inserimento di valori separati da virgole in SQL Server 2005

Dai un'occhiata a qualcosa come (Esempio completo)

DECLARE @Inserts TABLE(
        ID INT,
        Val1 INT,
        Val2 INT,
        Val3 INT
)

DECLARE @Param1 INT,
        @Param2 VARCHAR(100),
        @Param3 INT,
        @Param4 VARCHAR(100)

SELECT  @Param1 = 17,
        @Param2 = '127,204,110,198',
        @Param3 = 7,
        @Param4 = '162,170,163,170'

DECLARE @Table1 TABLE(
        ID INT IDENTITY(1,1),
        Val INT
)

DECLARE @Table2 TABLE(
        ID INT IDENTITY(1,1),
        Val INT
)

DECLARE @textXML XML        

SELECT    @textXML = CAST('<d>' + REPLACE(@Param2, ',', '</d><d>') + '</d>' AS XML)
INSERT INTO @Table1
SELECT  T.split.value('.', 'nvarchar(max)') AS data
FROM    @textXML.nodes('/d') T(split)

SELECT    @textXML = CAST('<d>' + REPLACE(@Param4, ',', '</d><d>') + '</d>' AS XML)
INSERT INTO @Table2
SELECT  T.split.value('.', 'nvarchar(max)') AS data
FROM    @textXML.nodes('/d') T(split)

INSERT INTO @Inserts
SELECT @Param1,
        t1.Val,
        @Param3,
        t2.Val
FROM    @Table1 t1 INNER JOIN
        @Table2 t2 ON t1.ID = t2.ID

SELECT *
FROM @Inserts