日期:2014-05-17  浏览次数:20486 次

SQL语句 update 能不能把修改的列和值一次性赋值给一个参数传过来
有a,b,c 3个表,a表是b表的主表
a表的列为
aid....(其它与这个问题无关的列)
b表
bid aid fieldname value
1 1 c.name 张三
2 1 c.sex 女
c表
cid name sex age 等等
1 李四 男 18

知道aid=1、cid=1。根据aid 查询出b表的数据,其中fieldname为c表的列名,value为对应列的值,然后修改c表的数据
这个update的SQL语句应该怎么写
我想把查出来的B表数据的fieldname和value拼成一个参数,名为field="c.name='张三',c.sex='女'"
update c set @field where cid = @cid
这样写会报where 附近语法有错误,有没有什么办法实现这个功能。
如果写存储过程 把所有的列全部写出来 那样的话 我这表有100多列 参数太多 而且传过来的值还要判断他对应的是哪个列。我想把修改的列和值一起传过来

------解决方案--------------------
使用动态SQL来实现
------解决方案--------------------
你要么把整句update拼接成动态sql来执行,要么使用case when来实现。
------解决方案--------------------
SQL code

declare @sql nvarchar(max)
select @sql=isnull(@sql,'')+stuff((select ','+fieldname+'=N'''+[value]+'''' from b
where aid=1 for xml path('')),1,1,'')
set @sql='update c set '+@sql+' where cid=1'
exec(@sql)