• 用存储过程处理插入值重复时(如果插入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 

  • 相关阅读:
    zookeeper logs is missing zookeeper 日志丢失
    Java Spring IoC 学习(3)
    jsp中include的两种用法
    java多态
    Referenced file contains errors
    类的初始化顺序
    PHP处理session跨域
    Apache中按天分割日志(Windows)
    redis和memcached的区别(总结)
    PHP中的traits简单理解
  • 原文地址:https://www.cnblogs.com/Roy_88/p/5463116.html
Copyright © 2020-2023  润新知