日期:2014-05-19  浏览次数:20527 次

SQL里条件判断后怎么使用增加语句?
想实现如下:
如果发现数据表中存在某条记录则更新,如果不存在就增加一条记录,
select   *   from   table   where   nYear=1000   and   nMonth=12   and   nDay=31
如果该记录存在则执行
update   table   set   nMoney=nMoney+10   where   nYear=1000   and   nMonth=12   and   nDay=31
如果不存在就执行
insert   into   table   (nMoney,nYear,nMonth,nDay)   values   (100,1000,12,31)

如果合在一起怎么写??

再有一个问题,SQL语句有没有最大长度的限制?

------解决方案--------------------
if exists(select 1 from table where nYear=1000 and nMonth=12 and nDay=31)
update table set nMoney=nMoney+10 where nYear=1000 and nMonth=12 and nDay=31
else
insert into table (nMoney,nYear,nMonth,nDay) values (100,1000,12,31)
------解决方案--------------------
if exists(select * from table where nYear=1000 and nMonth=12 and nDay=31)
update table set nMoney=nMoney+10 where nYear=1000 and nMonth=12 and nDay=31
else
insert into table (nMoney,nYear,nMonth,nDay) values (100,1000,12,31)
------解决方案--------------------
非动态sql好像没有吧,就算有也是很大的。。
------解决方案--------------------
包含 SQL 语句的字符串长度(批处理大小):65,536 * 网络数据包大小1
------解决方案--------------------
declare @cnt int

select @cnt = count(*) from table where nYear=1000 and nMonth=12 and nDay=31
if (@cnt = 1)
begin
update table set nMoney=nMoney+10 where nYear=1000 and nMonth=12 and nDay=31
end
else
begin
insert into table (nMoney,nYear,nMonth,nDay) values (100,1000,12,31)
end