如何将字符串拆分并插入SQL Server表?

时间:2017-12-08 06:58:20

标签: sql sql-server

我需要在IMS080','IMS108','IMS218中将这些temptable值插入单独的行中,如下所示:

row 1: IMS080
row 2: IMS108
row 3: IMS218

查询:

INSERT INTO #TableName
    SELECT UserID 
    FROM ('IMS080', 'IMS108', 'IMS218') 

提前致谢

4 个答案:

答案 0 :(得分:1)

您可以将所有ID添加到以逗号分隔的一个字符串中,并将其拆分为每一行。这对你有帮助。

INSERT INTO #TableName
SELECT Split.a.value('.', 'VARCHAR(100)') AS USERID  
FROM 
(
    SELECT CAST ('<M>' + REPLACE('IMS080,IMS108,IMS218', ',', '</M><M>') + '</M>' AS XML) AS Data  
)AS A CROSS APPLY Data.nodes ('/M') AS Split(a); 

答案 1 :(得分:0)

您可以使用union

Insert into #TableName
SELECT 'IMS080' UserID
union 
select 'IMS108' UserID
union 
select 'IMS218' UserID

修改:

Insert into #TableName
values ('IMS080'), ('IMS108'), ('IMS218')    

答案 2 :(得分:0)

    CREATE TABLE #TableName(ID int identity(1,1),userid varchar(50));
    INSERT INTO #TableName
        SELECT value as UserID FROM  STRING_SPLIT('IMS080,IMS108,IMS218',',') ORDER BY value

    SELECT * FROM #TableName

------------
ID  userid
----------
1   IMS080
2   IMS108
3   IMS218

答案 3 :(得分:0)

INSERT INTO #TableName
    SELECT UserID 
    FROM  ( VALUES ('IMS080')
                 , ('IMS108')
                 , ('IMS218')
         ) AS X (UserId)