A表
id int
name varchar(50)
B表
id int
name varchar(50)
topid intB表的topid引用的是A表的id
B表的name 引用的是A表的name 求:当我在B表中 输入相关name值的时候topid自动对应A表中于B表当前name相同的数据的id
sql关联语句怎么写才能实现

解决方案 »

  1.   

    select id from A where name=@bName
    然后再插入相应的ID
      

  2.   

    不是查询语句 我是要写类似外键这样的关联 关联后再B表中插入数据时只需要插入name, topid即可自动匹配  明白?
      

  3.   

    insert into B select Bid, id,name from A where name=@bName 
      

  4.   

    insert into B (id, name) VALUES (1, 'name'); 
    我要的是像上面这样的 不输入topid的情况下 插入到数据库中 而实际数据库中是topid已经自动对应了A表中的相关ID这样的功能
      

  5.   

    create table a (id int, [name] varchar(50));
    insert into a select 1,'Tom'
     union all select 2,'Jerry'
     union all select 3,'Sam'
    select * from acreate table b (id int, [name] varchar(50) not null, topid int);
    create trigger trg_name on b
    for insert,update
    as
     if exists (select [name] from inserted
     where [name] not in (select [name] from a)
     or (topid is not null and topid not in (select topid from a)))
      rollback tran; update b set b.topid=a.id
     from a, b where a.[name]=b.[name];
    goinsert into b (id,[name])
     select 1,'Tom' union all
     select 2,'Sam' update b set [name]='Jerry' where id=1select * from b