使用sql在表中插入两个或多个逗号分隔值

时间:2017-05-28 11:25:06

标签: sql sql-server sql-server-2008

我想尝试在表中插入两个变量,用逗号分隔值,但我不知道如何插入它

我的情况如下

我创建临时表

var str = UrlFetchApp.fetch('www.php.net').getContentText();
var regExp = new RegExp("general-purpose(.{0,10})", "gi");
var response = regExp.exec(str)[1];
Logger.log(response);

现在声明两个值为

的变量
create table #temp (sku varchar(10), qty int)

现在我想在#temp表中插入此变量 我有分裂功能。 我试过下面的查询

declare @sku varchar(200) = 'RCLET0005,RCLET0015';
declare @qty varchar(100) = '2,1';

3 个答案:

答案 0 :(得分:0)

你可以这样做..

WITH cte AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY null) as rn, value FROM [dbo].[fn_Split](@sku, ',')
    UNION
    SELECT 2+(row_number() OVER(ORDER BY null)) as rn, value FROM [dbo].[fn_Split](@qty, ',')
)

INSERT INTO #temp
SELECT c1.value,c2.value
FROM cte c1 
    INNER JOIN cte c2 ON c2.rn = c1.rn+1 AND c1.rn IN (1,3) AND c2.rn IN (2,4)

答案 1 :(得分:0)

您的fn_Split函数需要返回每个值的序号位置,以便可以关联单独的列表。下面是使用派生表子查询的示例。您也可以使用CTE或CROSS APPLY。

INSERT INTO #temp (sku,qty) 
SELECT 
      sku.value
    , qty.value
FROM (SELECT ordinal_position, value FROM [dbo].[fn_Split](@sku, ',') AS sku
JOIN (SELECT ordinal_position, value FROM [dbo].[fn_Split](@qty, ',') AS qty ON
    sku.ordinal_position = qty.ordinal_position;

答案 2 :(得分:0)

假设每个字符串中没有重复这些值,并且您的分割函数没有返回该位置,您可以这样做:

with s as (
      select value,
             row_number() over (order by (select null)) as pos
      from dbo.fn_Split(@sku, ',')
     ),
     q as (
      select value,
             row_number() over (order by (select null)) as pos
      from dbo.fn_Split(@qty, ',')
     )
insert into #temp (sku,qty)
    select s.value, q.value
    from s join
         q
         on s.pos = q.pos;

以下CTE可能在没有这些假设的情况下工作 - 但由于排序不稳定,代码不能保证工作:

with s as (
      select value,
             row_number() over (order by charindex(value, @sku)) as pos
      from dbo.fn_Split(@sku, ',')
     ),
     q as (
      select value,
             row_number() over (order by charindex(value, @qty)) as pos
      from dbo.fn_Split(@qty, ',')
     )

替代解决方案不使用fn_split()。他们会使用递归CTE或XML。