SQL Server初学者:如何从另一个表更新表数据?

| 我仍在学习SQL。我有关于更新表的问题。如何基于其他表更新我的表?请参见以下示例:
create table batch_info (
    batch_key int identity(1, 1) not null primary key,
    batch_num int not null,
    batch_name varchar(50) null,
    batch_start datetime null,
    batch_end datetime null,
    table_name varchar(50) null,
    insert_rows int null
)
go

insert into batch_info (batch_num, batch_name, batch_start)
    values (\'32\', \'Batch_to_insert_rows\', \'20110414\')
go

select * from batch_info

create table ref_table (
    bat_num int not null,
    bat_end_date datetime null,
    bat_table_name varchar(50) null,
    bat_ins_rows int null,
)
go

insert into ref_table 
    values  (\'32\',\'20110414 02:12:00.000\',\'Table1\',\'10\'),
            (\'32\',\'20110414 02:12:00.000\',\'Table2\',\'33\'),
            (\'32\',\'20110414 02:12:00.000\',\'Table3\',\'12\') 

select * from ref_table

--How can I update batch_info table to get this info?
select 
bi.batch_key, 
bi.batch_num, 
bi.batch_name,
bi.batch_start,
rt.bat_end_date,
rt.bat_table_name, 
rt.bat_ins_rows
 from batch_info as bi
inner join ref_table as rt on bi.batch_num = rt.bat_num
编辑:批处理键是代理,所以它应该是增量的,而不是像我的联接查询中的(1、1、1、1)。     
已邀请:
假设batch_num和bat_end_date的组合是唯一的,那么这应该可以解决问题:
update  batch_info 
set     batch_end = rt.bat_end_date,
        table_name = rt.bat_table_name,
        insert_rows = rt.bat_ins_rows 
from    batch_info bi
        inner join ref_table rt on rt.bat_num = bi.batch_num 
        inner join 
        (
            select  bat_num,
                    MIN(bat_end_date) as min_bat_end_date
            from    ref_table 
        ) oldest on oldest.bat_num = rt.bat_num 
                    and oldest.min_bat_end_date = rt.bat_end_date 
where   bi.batch_end is null

insert into batch_info 
(batch_num, batch_name, batch_start, batch_end, table_name, insert_rows)
select  bi.batch_num,
        bi.batch_name,
        bi.batch_start,
        rt.bat_end_date,
        rt.bat_table_name,
        rt.bat_ins_rows 
from    batch_info bi
        inner join ref_table rt on rt.bat_num = bi.batch_num 
where   not exists 
        (
            select   * 
            from     batch_info e 
            where    e.batch_num = bi.batch_num 
                     and e.batch_end = rt.bat_end_date
        )
如果值的另一种组合建立了唯一性,则可以在第一个查询中将这些值添加到ѭ2and,在第二个查询中将其添加到
e
。 我同意@Jim认为应该将其分为两个表。执行此操作的困难预示了该设计将要创建的困难。您试图将两个不同的东西(批处理和批处理运行)放入一个表中,这从来都不是一个好主意。     
insert into batch_info
SELECT batch_num, batch_name, batch_start,
bat_end, bat_table_name, bat_ins_rows
FROM batch_info inner join ref_table
on batch_info.batch_num = ref_table.bat_num

delete from batch_info
where batch_end is null
编辑:ѭ5会生成所有匹配的行并重新插入。新的身份值将添加到这些值中。现有行(其他字段为null)用于“ 5”语句,随后使用第二条语句删除。     
我本来是要向您指出“合并声明”的,但是我也不认为这可以做到。我认为您将不得不使用游标卡住。 如此说而又不知道您的现有需求,它实际上应该是两个表。将全部推入一张桌子将使桌子设计不规范。     
使batch_info.batch_key字段自动递增。
create table batch_info (
batch_key int identity(1, 1) not null primary key, -- <<- make autoincrement.
...
    

要回复问题请先登录注册