表A
ID (int)  name (varchar(50))ID   name
 1    中国
 2    美国表B
ID (int)    AID (int) 
ID  AID
1   1
2   2
3   1表C  
ID (int)  BID(int)   SSS(int) BBB(int)ID   BID   SSS  BBB
1     1     3     0
2     2     3     0
3     1     2     0
4     1     3     0
5     2     3     0
6     1     9     0求一个存储过程
exec '美国'
实现 表C中MAX(sss)对应的BBB更新为2面试题

解决方案 »

  1.   


    declare @id int=0;
    select @id =Id from 表A where name='美国'update 表C
    set BBB=@id
    where sss=(select MAX(sss) from 表C)
      

  2.   


    中间还有一个表B呢exec '美国'
    1.在表A中查询 '美国对应的ID'
    2 根据 1的ID查找表B中对应的ID
    3.再根据2的ID在表C查找到对应数据中 并要求把SSS最大的那一项的BBB改成2
      

  3.   

    if object_id('Tempdb..#a') is not null drop table #a
    if object_id('Tempdb..#b') is not null drop table #b
    if object_id('Tempdb..#c') is not null drop table #c
    create table #a(
     ID int not null,
     [name] nvarchar(100) null
    )create table #b(
     ID int   not null,
     [AID] int null
    )create table #c(
     ID int  not null,
     [BID] int null,
     [SSS] int null,
     [BBB] int null
    ) Insert into #a
    select 1,'中国' union all
    select 2,'美国'insert into #b
    select 1,1 union all
    select 2,2 union all
    select 3,1 insert into #c
    select 1,1,3,0 union all
    select  2,2,3,0 union all
    select  3,1,2,0 union all
    select  4,1,3,0 union all
    select  5,2,3,0 union all
    select  6,1,9,0select * from #a
    select * from #b
    select * from #c
    -------------把下边的修改一下即可
    declare @name nvarchar(100)
    set @name='美国'
    ;with cte as(
    select c.ID,max(c.SSS)sss from #c c
    join #b b on b.ID=c.BID
    join #a a on a.ID=b.AID
    where a.name=@name
    group by c.ID
    )
    update #c set BBB=2 where ID in(select ID from cte)
    select * from #c-------------------------------
    ID          BID         SSS         BBB
    ----------- ----------- ----------- -----------
    1           1           3           0
    2           2           3           2
    3           1           2           0
    4           1           3           0
    5           2           3           2
    6           1           9           0(6 行受影响)
      

  4.   


    --上边代码中的这些语句只是为了显示下数据,可以去掉
    select * from #a
    select * from #b
    select * from #c