将数据从一个表移动到另一个表,重复行

时间:2014-04-30 06:54:01

标签: sql-server sql-server-2005

我正在编写此查询以将数据从一个表移动到另一个表。

目标表

Task
id
assignedtoid
decription

来源表

 id
 taskid
 comments

查询

UPDATE
    Task
SET
    Task.[Description] = TMC.Comment
FROM
    Task    
INNER JOIN     
    TaskComment TMC 
ON     
    Task.Id = TMC.TaskId
WHERE
    Task.AssignToId in(some ids)

问题:有些任务有多个评论没有随此查询移动吗?

我们如何实现它,我使用的是sql server 2005

1 个答案:

答案 0 :(得分:0)

只需稍微更改您的查询,但您没有获得其他注释数据,因为您的任务表中不存在这些新记录。因此,您必须从TaskComment表中插入这些新记录。

UPDATE
    Task
SET
    [Description] = TMC.Comment
FROM
    Task t   
INNER JOIN     
    TaskComment TMC 
ON     
    t.Id = TMC.TaskId
WHERE
    t.AssignToId in (1,2,3)

要在SQL Server 2008中实现此目的,您可以使用MERGE语句,但由于您使用的是SQL Server 2005,因此您可以使用另一种方法(从此处获取的构思mimicking-merge-statement-in-sql),如下所述,并提供示例。

-- Create table1
CREATE TABLE Table1 (Col1 INT, Col2 INT, Col3 VARCHAR(100))
INSERT INTO Table1 (Col1, Col2, Col3)
SELECT 1, 11, 'First'
UNION ALL
SELECT 11, 12, 'Second'
UNION ALL
SELECT 21, 13, 'Third'
UNION ALL
SELECT 31, 14, 'Fourth'
GO
-- Create table2
CREATE TABLE Table2 (Col1 INT, Col2 INT, Col3 VARCHAR(100))
INSERT INTO Table2 (Col1, Col2, Col3)
SELECT 1, 21, 'Two-One'
UNION ALL
SELECT 11, 22, 'Two-Two'
UNION ALL
SELECT 21, 23, 'Two-Three'
UNION ALL
SELECT 31, 24, 'Two-Four'
UNION All
SELECT 21, 33, 'Two-Six'
UNION ALL
SELECT 31, 34, 'Two-Nine'
GO

SELECT *
FROM Table1
SELECT *
FROM Table2
GO


declare @updated_ids table(col2 int)
UPDATE Table1
SET Col2 = t2.Col2,
Col3 = t2.Col3
output inserted.col2 into @updated_ids
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.Col1 = t2.Col1
WHERE t1.Col1 IN (21, 31)

insert into Table1
select col1, col2, col3 from Table2 
where col2 not in(select col2 from @updated_ids)
go

DROP TABLE Table1
DROP TABLE Table2

所以在你的情况下,你应该做类似

的事情
declare @updated_ids table(id int)
UPDATE
    Task
SET
    [Description] = TMC.Comment
output inserted.Id into @updated_ids
FROM
    Task t   
INNER JOIN     
    TaskComment TMC 
ON     
    t.Id = TMC.TaskId
WHERE
    t.AssignToId in (1,2,3)

    insert into Task
    select id,
    taskid,
    comments 
    from TaskComment 
    where taskid not in (select id from @updated_ids)
    go