在MSSQL中将某些字段从一个表复制到另一个表

时间:2015-07-22 09:47:35

标签: sql sql-server

我正在尝试从一个表到另一个表完成某些行的字段的副本。我正在尝试使用此查询:

update table1
set goal = t2.Goal, notes = t2.Notes
from
    Table2 AS t2
    join Table3 AS t3
        ON t3.ID = t2.PID
    join table1 as t1
        on t1.title = Title 
        and Name like t1.name + '%' 

我需要加入前两个表来获取名称和标题,第三个名称和标题使用标题和名称作为标识符。此查询有效,但不适用于table1中的所有行 - 有一些行没有复制数据。 我做错了什么?

2 个答案:

答案 0 :(得分:4)

我认为你需要做这样的事情:

update t1
set t1.goal = t2.Goal, t1.notes = t2.Notes
from
    Table2 AS t2
    JOIN Table3 AS t3 ON t3.ID = t2.PID
    JOIN table1 as t1 ON t1.title = t3.Title 
    AND t2.Name like t1.name + '%'

答案 1 :(得分:1)

尝试这样的事情......

update Table1 
  set Goal = t2.Goal,
      Notes = t2.Notes
from
   Table2 AS t2
   join Table3 AS t3
        ON t3.ID = t2.PID 
where  
   Table1.Title = t3.Title AND
   t2.Name like (Table1.Name + '%')

以下是基于您的架构http://sqlfiddle.com/#!6/a08cc/1

的示例