Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Insertion de valeurs séparées par des virgules dans SQL Server 2005

Jetez un coup d'œil à quelque chose comme (Exemple complet)

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