在SQL Server中插入逗号分隔值和一些常量值

时间:2017-05-22 20:17:27

标签: sql-server

我有一个逗号分隔的字符串,如“1,2,3,4,5,6,7”,我想在表列中插入此值,其他值是常量,如

Insert into tbl(value1, value2, value3) values(@v1, @v2, 1)
Insert into tbl(value1, value2, value3) values(@v1, @v2, 2)
Insert into tbl(value1, value2, value3) values(@v1, @v2, 3) etc.

其中@ v1,@ v2值始终是常数。

那我该如何编写查询?

2 个答案:

答案 0 :(得分:2)

在SQL Server 2016+中,您可以使用string_split()

在2016年之前的SQL Server中,使用Jeff Moden的CSV Splitter表值函数:

create table tbl (value1 int, value2 int, value3 int);
declare @v1 int = 0;
declare @v2 int = -1;
declare @var varchar(8000) = '1,2,3,4,5,6,7';

insert into tbl 
  select @v1, @v2, s.Item
  from delimitedsplit8K(@var, ',') s

select * from tbl;

rextester演示:http://rextester.com/GBVJS38200

返回:

+--------+--------+--------+
| value1 | value2 | value3 |
+--------+--------+--------+
|      0 |     -1 |      1 |
|      0 |     -1 |      2 |
|      0 |     -1 |      3 |
|      0 |     -1 |      4 |
|      0 |     -1 |      5 |
|      0 |     -1 |      6 |
|      0 |     -1 |      7 |
+--------+--------+--------+

拆分字符串参考:

答案 1 :(得分:1)

如果您需要内联版本

示例

Declare @v1 varchar(25) = 'SomeValue'
Declare @v2 varchar(25) = 'OtherValue'
Declare @S  varchar(max)= '1,2,3,4,5,6,7'

Insert Into tbl (value1, value2, value3)
Select @v1,@v2,RetVal
 From (
        Select RetSeq = Row_Number() over (Order By (Select null))
              ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
        From  (Select x = Cast('<x>' + replace((Select replace(@S,',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
        Cross Apply x.nodes('x') AS B(i)
      ) A

插入的行看起来像

enter image description here