2010-08-13 43 views
1

我有两个表,其既包含 '管分隔值'合并两个场而一只有新项目

例如:

表1:

DataField_A 

item 1|item 2|item 3|etc..... 

表2:

DataField_A 

item 7|item 5|item 3|etc..... 

我需要将表2合并到表1中,以便表2包含两个表中的所有项目。

这样做亲语法是通过每个项目在表2中循环,并增加表1的简单的事情,如果它不存在表1

如何在SQL中完成作为存储程序?

+0

如何将这些表链接起来? – 2010-08-13 15:41:26

+0

@OMG是的,这是正确的。 @Michael,这两个表都有链接它们的linkId,例如表1有LinkId,表2也有LinkId – Darknight 2010-08-13 15:46:09

+0

这是用于SQL Server 2005的吗?我已经重新读过你的问题 - 你有非规范化的数据,并且你想把更多非规范化的数据合并到一个表中?呃... – 2010-08-13 15:53:42

回答

1

我已经使用了一个解析函数(我使用的示例来自here)来解析Table1中的字符串。然后,我在CTE中使用该函数来查找表2中的缺失元素并合并数据。

/* Helper function to parse delimited string */ 
CREATE FUNCTION [dbo].[fnParseStringTSQL] (@string NVARCHAR(MAX),@separator NCHAR(1)) 
RETURNS @parsedString TABLE (string NVARCHAR(MAX)) 
AS 
BEGIN 
    DECLARE @position int 
    SET @position = 1 
    SET @string = @string + @separator 
    WHILE charindex(@separator,@string,@position) <> 0 
     BEGIN 
     INSERT into @parsedString 
     SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position) 
     SET @position = charindex(@separator,@string,@position) + 1 
     END 
    RETURN 
END 
go 

/* Set up some sample data */ 
declare @Table1 table (
    id int, 
    DataField_1A varchar(500) 
) 

declare @Table2 table (
    id int, 
    DataField_2A varchar(500) 
) 

insert into @Table1 
    (id, DataField_1A) 
    select 1, 'item 1|item 2|item 3' 
    union 
    select 2, 'item A|item B|item C|item D|item Z' 

insert into @Table2 
    (id, DataField_2A) 
    select 1, 'item 7|item 5|item 3' 
    union 
    select 2, 'item A|item Y|item Z' 

/* data before the update */ 
select * from @Table2 

/* boolean to ensure loop executes at least once */ 
declare @FirstLoop bit 
set @FirstLoop = 1 

/* Do the updates */ 
while (@FirstLoop = 1 or @@ROWCOUNT <> 0) begin 
    set @FirstLoop = 0 

    ;with cteMissingItems as (
    select t2.id, p.string 
     from @Table2 t2 
      inner join @Table1 t1 
       on t2.id = t1.id 
      cross apply dbo.fnParseStringTSQL(t1.DataField_1A,'|') p 
     where charindex(p.string, t2.DataField_2A) = 0 
    ) 
    update t2 
     set t2.DataField_2A = t2.DataField_2A + '|' + mi.string 
     from @Table2 t2 
      inner join cteMissingItems mi 
       on t2.id = mi.id 
end /* while */ 

/* Prove the update worked */ 
select * from @Table2 

/* Clean up */ 
drop function dbo.fnParseStringTSQL 
+0

优秀!我会试试这个。如果有效,我会将其标记为可接受的解决方案。非常感谢! – Darknight 2010-08-15 02:18:35