日期:2014-05-18  浏览次数:20580 次

求助:如果unique键有记录则更新记录,如果没有则插入。某个值为1更新字段1,该值为2则更新字段2.....依次类推。求sql语句该如何写
如题:
1、如果唯一键在表中已有记录,则更新其相应字段,如果没有则插入一条新纪录
2、更新的时候,如果一个参数值为1,则更新字段1,如果该参数值为2,则更新字段2,依次类推

求助各位大侠sql语句该怎么写,急急急!!!!

------解决方案--------------------
if exists (select top 1 * from t where id = @id)
begin
if @c = 1
begin
update t
set c1 = @cv
end
else
begin if @c = 2
update t
set c2 = @cv
end
end
else
insert into t (c1) values (@cv);
end

自己再根据实际内容写吧
------解决方案--------------------
1、

if exists (select 1 from tb where 唯一列 = @参数)
insert into tb...
else
update tb
set ...
where 唯一列 = @参数

2、

这种更新要用动态去执行,列名有什么规律么?按照传入的参数值去拼接更新的SQL语句。

declare @str varchar(max)
declare @i int
set @str = 1
set @i = 1
set @str = (case when @i=1 then 'col1' when @i=2 then 'col2' else 'col3' end)
set @str = ' update tb set '+@str+' = ... where ... '
exec(@str)