• SQLServer用存储过程实现插入更新数据


    实现

    1)有同样的数据,直接返回(返回值:0);

    2)有主键同样,可是数据不同的数据,进行更新处理(返回值:2);

    3)没有数据,进行插入数据处理(返回值:1)。


    【创建存储过程】

    Create proc Insert_Update  

     
    @Id varchar(20),  
     
    @Name varchar(20),  
     
    @Telephone varchar(20),  
     
    @Address varchar(20),  


    @Job varchar(20), 
     
    @returnValue int output  
     
    as  
     
    declare  
     
    @tmpName varchar(20),  
     
    @tmpTelephone varchar(20),


    @tmpJob varchar(20),
     
    @tmpAddress varchar(20)
     
    if exists(select * from dbo.DemoData where id=@Id)  
     
    begin  
     
    select @tmpName=Name,@tmpTelephone=Telephone,@tmpAddress=Address,@tmpJob=Job from dbo.DemoData where id=@Id  
     
    if ((@tmpName=@Name) and (@tmpTelephone=@Telephone) and (@tmpAddress=@Address)and (@tmpJob=@Job))  
     
    begin  
     
    set @returnValue=0 --有同样的数据。直接返回值  
     
    end  
     
    else  
     
    begin  
     
    update dbo.DemoData set Name=@Name,Telephone=@Telephone,Address=@Address,Job=@Job where id=@Id  
     
    set @returnValue=2 --有主键同样的数据,进行更新处理  
     
    end  
     
    end  
     
    else  
     
    begin  
     
    insert into dbo.DemoData values(@Id,@Name,@Telephone,@Address,@Job)  
     
    set @returnValue=1 --没有同样的数据,进行插入处理  
     
    end 


    【运行方式】

    declare @returnValue int   
    exec Insert_Update '15','hugh15','3823345','长安街','副部长',@returnValue output  
    select @returnValue


    返回值0。已经存在同样的

    返回值1。插入成功

    返回值2,更新成功


  • 相关阅读:
    【数据结构】平衡二叉树之AVL树
    【数据结构】二叉排序树BST
    【数据结构】二叉树
    【算法】堆排序
    【数据结构】堆
    第五百八十一天 how can I 坚持
    第五百八十天 how can I 坚持
    第五百七十八、九天 how can I 坚持
    第五百七十七天 how can I 坚持
    第五百七十五、六天 how can I 坚持
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10619781.html
Copyright © 2020-2023  润新知