使用不同表中的列值更新表的列值

时间:2014-05-28 03:08:13

标签: sql sql-server

我有一个表格Table 1),其中包含FNLNMN列以及其他十一列。我有另一张表Table 2),其中有FNLNMN(只有三列)。

我想更新FN中我的值LNMNTable 1,其值为FNLN和{{ 1}}来自MN

我不需要在任何其他常见专栏的基础上加入。

如果有办法,请告诉我。

我不能使用Table 2语句,因为两个表的结构不一样。 SELECT * INTO有11个奇数列,Table 1有3列。

2 个答案:

答案 0 :(得分:1)

如果Table 1包含:

[FN]           [LN]     [MN]    [A]          [B]     [C]
--------------------------------------------------------
hello          world     123    something    else    456
other          row        45    demo         data    789
something      else      456    NULL         NULL    999

Table 2包含:

[FN]           [LN]     [MN]
----------------------------
table          two         1
just-a-demo    here        2
final          row         3

,预期结果是:

[FN]           [LN]     [MN]    [A]          [B]     [C]
--------------------------------------------------------
table          two         1    something    else    456
just-a-demo    here        2    demo         data    789
final          row         3    NULL         NULL    999

你可以先得到这样的预期结果;

select [S].[FN], [S].[LN], [S].[MN], [F].[A], [F].[B], [F].[C] from
(
    select top 10
        row_number() over (order by (select 1)) as [Id], [A], [B], [C]
    from [Table 1]
) as [F]
left join
(
    select top 10
        row_number() over (order by (select 1)) as [Id], [FN], [LN], [MN]
    from [Table 2]
) as [S]
on [F].[Id] = [S].[Id]

注意:

  • top 10:您可能需要删除它,但必须确保两个表都返回相同的行数。如果他们不这样做,则无法根据您在评论中提供的信息进行1:1映射。

  • row_number() over (order by (select 1))只需输入" 1"对于第一个返回的行," 2"这是一种奇怪的方式来加入两个表的结果:我希望在两个表中都有一个实际的ID,或者能够进行实际连接的东西。

然后,您可以将其插入临时表:

您可以做的是使用insert into和子查询select,如下所示:

insert into [TempTable] ([FN], [LN], [MN], [A], [B], [C])
    select [S].[FN], [S].[LN], [S].[MN], [F].[A], [F].[B], [F].[C] from
    (
        select top 10
            row_number() over (order by (select 1)) as [Id], [A], [B], [C]
        from [Table 1]
    ) as [F]
    left join
    (
        select top 10
            row_number() over (order by (select 1)) as [Id], [FN], [LN], [MN]
        from [Table 2]
    ) as [S]
    on [F].[Id] = [S].[Id]

然后将[Table 1]替换为[TempTable]

答案 1 :(得分:0)

这是你正在寻找的方式。

Declare @table1 Table
    (id int identity(1,1), 
    FN varchar(15), 
    LN varchar(15), 
    MN varchar(15),
    Flag1 int default(1),
    Flag2 int default(1),
    Flag3 int default(0))

Declare @table2 Table
    (id int identity(1,1), FN varchar(15), LN varchar(15), MN varchar(15))

Insert into @table1 (Fn,LN,MN) Values 
('A','B','C'),('A','B','D'),('A','X','C')
Insert into @table2 (Fn,LN,MN) Values 
('A','B','C'),('A','B','D'),('A','Y','C')

enter image description here

Merge into @table1 A
using @table2 B On 
        A.FN = B.FN AND
        A.LN = B.LN AND
        A.MN = B.MN
When Not Matched then
Insert (FN,LN,MN)
Values (B.FN,B.LN,B.MN); 

Select * from @table1

<强>结果

enter image description here