나는 구문 분석 함수를 사용하여 (예제에서는 내가 사용하고 있습니다 here)에서 Table1의 문자열을 구문 분석합니다. 그런 다음 해당 함수를 CTE에 사용하여 Table2의 누락 된 요소를 찾아서 데이터를 병합합니다.
/* 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
어떻게이 테이블에 링크되어 있습니까? –
@OMG 맞습니다. @Michael, 테이블 둘 다 링크 아이디가 있습니다. 예를 들어, 표 1에 LinkId가 있고 표 2에 LinkId가 있습니다. – Darknight
이것은 SQL Server 2005 용입니까? 귀하의 질문을 다시 읽었습니다 - 데이터를 비정규 화했습니다. * 더 많은 비정규 화 된 데이터를 단일 테이블로 병합 하시겠습니까? 아 ... –