将逗号分隔的varchar插入多个列值?

时间:2013-12-26 12:42:24

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

我有像这样的varchar字符串值

"AccountType","contains","Customer","Balance","equals",250,"FirstName","like","John"

现在我要插入此

在这样的表中

  FieldName       FieldContiion  FieldValue

  AccountType     contains       Customer
  Balance         equals         250
  FirstName       like           John

字符串变量的长度可以像这样改变

"Balance","equals",250,"FirstName","like","John"
这意味着它只会在表中插入两行。

2 个答案:

答案 0 :(得分:1)

您可以执行以下步骤:

1)为逗号分隔的字符串创建分割函数:

CREATE FUNCTION [dbo].[Split] (
    @InputString                  VARCHAR(8000),
    @Delimiter                    VARCHAR(50)
)

RETURNS @Items TABLE (
    Item                          VARCHAR(8000)
)

AS
BEGIN
    IF @Delimiter = ' '
    BEGIN
          SET @Delimiter = ','
          SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
    END

    IF (@Delimiter IS NULL OR @Delimiter = '')
        SET @Delimiter = ','

    DECLARE @Item                 VARCHAR(8000)
    DECLARE @ItemList       VARCHAR(8000)
    DECLARE @DelimIndex     INT

    SET @ItemList = @InputString
    SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
    WHILE (@DelimIndex != 0)
    BEGIN
          SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
          INSERT INTO @Items VALUES (@Item)

          SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
          SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
    END

    IF @Item IS NOT NULL
    BEGIN
          SET @Item = @ItemList
          INSERT INTO @Items VALUES (@Item)
    END

    ELSE INSERT INTO @Items VALUES (@InputString)

    RETURN

END

2)创建一个过程,以逗号分隔的字符串作为参数接收。在这个例子中,我使用的是固定字符串,但您应该修改它以使其与参数一起使用。 注意:我考虑到你的目标表总是有3列,并且逗号分隔的字符串的长度总是3的倍数...如果这个改变,你必须调整程序......

/* Get the length of the comma separated string */
DECLARE @ITEM_COUNT INT

SELECT @ITEM_COUNT = COUNT(*) FROM
(
    SELECT  item
        FROM Split('"AccountType","contains","Customer","Balance","equals",250,"FirstName","like","John"',',')  
) N

declare @x int
set @x = 1

/* Insert in your table every 3 columns... */
WHILE (@x < @ITEM_COUNT)
BEGIN 

    insert into test 
    select /* pivoting the sub-query */
      fieldname = max(case when seq = @x then item end),
      fieldcondition = max(case when seq = @x + 1 then item end),
      fieldvalue = max(case when seq = @x + 2 then item end)
    from 
    (
        SELECT  item
               ,row_number() OVER (ORDER BY (SELECT 1)) AS seq 
                FROM Split('"AccountType","contains","Customer","Balance","equals",250,"FirstName","like","John"',',')  
    ) a

set @x = @x + 3

END

希望这有帮助

答案 1 :(得分:0)

将字符串拆分为分隔符(在您的情况下为,),然后迭代子字符串数组并插入表中。您的代码将类似于以下内容:

array subStrings[] = string.split(",");
int i=0;
while(i<len(subStrings)){
    // create query using the ith, (i+1)th and (i+2)th elements of the array
i=i+3;
}

上面代码中的一个假设是主字符串的元素只有3的倍数。