拆分逗号分隔字符串并插入表(int)

时间:2014-05-03 00:12:11

标签: sql-server

我有一个包含3列(First_ID,Second_ID,Third_ID)的表,所有列都是int列。

现在我有3个值,第一个和第三个值是int值(1和0),第二个值是逗号分隔的字符串('188,189,190,191,192,193,194'

我应该如何填充表格,如下所示:

1   188 0
1   189 0
1   190 0
1   191 0
1   192 0
1   193 0
1   194 0

我尝试了不同的方法,但无法按照我的意愿使用它。

提前致谢

4 个答案:

答案 0 :(得分:17)

最好使用XML,

imgThumbnail.setTag(<your image url>);
new DownloadImage().execute(imgThumbnail);

答案 1 :(得分:13)

使用您在评论中提到的Split()功能,

-- Variable holding comma separated values
DECLARE @Var VARCHAR(4000);
SET @Var =  '188,189,190,191,192,193,194'

-- Test Target Table
DECLARE @Target_Table TABLE  (First_ID INT,Second_ID INT,Third_ID INT) 

-- Insert statement
INSERT INTO @Target_Table
SELECT 1, CAST(Items AS INT) , 0 
FROM  dbo.Split(@Var, ',')  

-- Test Select
SELECT * FROM  @Target_Table  

结果集

╔══════════╦═══════════╦══════════╗
║ First_ID ║ Second_ID ║ Third_ID ║
╠══════════╬═══════════╬══════════╣
║        1 ║       188 ║        0 ║
║        1 ║       189 ║        0 ║
║        1 ║       190 ║        0 ║
║        1 ║       191 ║        0 ║
║        1 ║       192 ║        0 ║
║        1 ║       193 ║        0 ║
║        1 ║       194 ║        0 ║
╚══════════╩═══════════╩══════════╝  

答案 2 :(得分:2)

从SQL Server 2016开始,您可以使用此功能string_split

DECLARE @Var VARCHAR(4000);
SET @Var =  '188,189,190,191,192,193,194'

SELECT 1 as First_ID, value as Second_ID ,0 as Third_ID FROM string_split(@Var,',')

答案 3 :(得分:0)

DECLARE @Table VARCHAR(100)='AAA,BBB,CCC,DDD'
IF OBJECT_ID('[Comma_Split]') IS NOT NULL
DROP TABLE [Comma_Split]
CREATE TABLE [Comma_Split](ID INT IDENTITY(1,1),COL VARCHAR(100))
while LEN(@Table)>0
BEGIN
DECLARE @COMMA INT= CHARINDEX(',', @Table)
IF @COMMA=0 SET @COMMA=LEN(@Table)+1
INSERT INTO [Comma_Split]
SELECT SUBSTRING(@Table,1,@COMMA-1)
SET @COMMA=@COMMA+1
SET @Table=SUBSTRING(@Table,@COMMA,LEN(@Table))
END