用存储过程处理插入值重复时(如果插入id值存在时,在存在id值增1后再插入)

用存储过程处理插入值重复时(如果插入id值存在时,在存在id值增1后再插入)
create table ta(id int primary key,name varchar(20))
insert ta
select 1,'a'
union all select 2,'b'
union all select 3,'c'
union all select 12,'d'
union all select 13,'e'

用存储过程:
create proc test_p @id int,@name varchar(20)
as
begin
declare @j int,@sql varchar(1000)
if exists(select 1 from ta where id=@id)
begin
select @j=@id,@sql=''
while exists(select 1 from ta where id=@j)
begin
select @sql=@sql+','+rtrim(id) from ta where id=@j
select @j=@j+1
end
set @sql=stuff(@sql,1,1,'')
exec('update ta set id=id+1 where id in ('+@sql+')')
insert ta select @id,@name
end
else
insert ta select @id,@name
end

测试:
exec test_p 1,'f'
exec test_p 8,'h'
exec test_p 12,'g'
查询:
select * from ta

id          name                
----------- --------------------
1           f
2           a
3           b
4           c
8           h
12          g
13          d
14          e

(所影响的行数为 8 行)
--drop proc test_p
--drop table ta 

你可能感兴趣的:(SQL,Server技巧)