表A
时刻    待更新的列名        更新内容
1           c               11
2           a               22
3           d               33
4           e               44
表B
时刻      a      b      c      d      e
1                      11
2         22
3                             33
4                                     44
如何通过A表对B表更新,每个时刻所要更新的列名和内容必须通过对表A查询得知

解决方案 »

  1.   

    动态拼出sql语句再执行!
    declare @sql varchar(8000)
    set @sql=''
    select @sql=@sql+'    update 表B set '+ 待更新的列名+'='+更新内容 +' where 时刻='+时刻   from 表A
    exec(@sql)
      

  2.   

    RunUpwind() 的回答好象可以哦
      

  3.   

    需要用动态SQL语句。二楼提供的方法可行,需要改进一下:declare @sql varchar(8000)
    set @sql=''
    select @sql=@sql+'    update 表B set ['+ 待更新的列名+']='+更新内容 +' where 时刻='+时刻   from 表A
    exec(@sql)另外,更新的内容如果是字符型或日期新,则两侧需要加单引号
      

  4.   


    动态sql语句基本语法 
    1 :普通SQL语句可以用Exec执行 eg:   Select * from tableName 
             Exec('select * from tableName') 
             Exec sp_executesql N'select * from tableName'    -- 请注意字符串前一定要加N 2:字段名,表名,数据库名之类作为变量时,必须用动态SQL eg:   
    declare @fname varchar(20) 
    set @fname = 'FiledName' 
    Select @fname from tableName              -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。 
    Exec('select ' + @fname + ' from tableName')     -- 请注意 加号前后的 单引号的边上加空格 当然将字符串改成变量的形式也可 
    declare @fname varchar(20) 
    set @fname = 'FiledName' --设置字段名 declare @s varchar(1000) 
    set @s = 'select ' + @fname + ' from tableName' 
    Exec(@s)                -- 成功 
    exec sp_executesql @s   -- 此句会报错 declare @s Nvarchar(1000)  -- 注意此处改为nvarchar(1000) 
    set @s = 'select ' + @fname + ' from tableName' 
    Exec(@s)                -- 成功     
    exec sp_executesql @s   -- 此句正确 3. 输出参数 
    declare @num int, @sql nvarchar(4000) 
    set @sql='select count(*) from tableName' 
    exec(@sql) 
    --如何将exec执行结果放入变量中? declare @num int, @sql nvarchar(4000) 
    set @sql='select @a=count(*) from tableName ' 
    exec sp_executesql @sql,N'@a int output',@num output 
    select @num