请问我想新建一个表a,字段为id,name.
id是自动生成的序号从1开始自动分配,name是和表c.myname相同,c.myname更新的时候a.name也会同步,请问如何写命令

解决方案 »

  1.   

    create table ta(id int identity(1,1),name varchar(100))
    goname是和表c.myname相同,c.myname更新的时候a.name也会同步,请问如何写命令--
    在C上加一个触发器,
    create trigger tr_name
    on tablec
    for update 
    as
       update a set name = i.name
       from ta a
       right join inserted i on a.id = b.id --id是两表关联
    go
      

  2.   


    create table ta(id int identity(1,1),name varchar(100)) 
    go name是和表c.myname相同,c.myname更新的时候a.name也会同步,请问如何写命令 -- 
    在C上加一个触发器, 
    create trigger tr_name 
    on tablec 
    for update 
    as 
      update a set name = i.name 
      from ta a 
      right join inserted i on a.id = b.id --id是两表关联 
    go
      

  3.   

    可以设置级联更新实现,比如IF object_id('tc','u') IS NOT NULL
    DROP TABLE tc
    IF object_id('ta','u') IS NOT NULL
    DROP TABLE ta
    GOcreate table tc(myname varchar(10) not null)
    go
    create table ta(id int identity(1,1) ,name varchar(10) not null)
    goinsert tc select 'aa'
    union all select 'bb'insert ta select 'aa'
    union all select 'bb'
    union all select 'aa'
    goselect * from tc
    /*
    aa
    bb*/
    select * from ta
    /*1 aa
    2 bb
    3 aa
    */--为tc创建主健
    alter table tc add constraint c_pk primary key (myname)
    go
    --为ta创建外健,并指定级联更新
    alter table ta add constraint a_fk foreign key (name) references tc(myname) on update cascade
    go
    --更新tc,看看是否ta也跟着变
    update tc set myname='xx' where myname='aa'
    go
    select * from tc
    /*
    bb
    xx*/
    select * from ta
    /*
    1 xx
    2 bb
    3 xx
    级联更新生效*/
    goalter table ta drop constraint a_fk
    go
      

  4.   

    谢谢各位,问题是我两表不需要关联,我只需要提取表a的name到表b,并在表b中加上序号就可以了,因为表a没有序号,我又不能改变表a的结构