Sql Server 存储过程 - 用户操作实例

Posted yanjiez

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sql Server 存储过程 - 用户操作实例相关的知识,希望对你有一定的参考价值。

用户的增删改查

新增

--新增用户
create procedure addDeviceUser
    @name nvarchar(36) ,
    @phone nvarchar(36) ,
    @password nvarchar(255)
as
begin
    if exists(select 1 from DeviceUser where [email protected]) --判断用户是否存在   
        select 1 from DeviceUser where 1!=1
    else
        begin
            insert into DeviceUser (id,name,phone,password) values(newid(),@name,@phone,@password)
            select id,name,phone from DeviceUser where [email protected]
        end
end

--执行
exec addDeviceUser @name='testname',@phone='18800000000',@password='123'

查询

--获取用户
alter procedure getDeviceUser
    @id nvarchar(36),
    @phone nvarchar(36)
as
begin
    if(@id=''and @phone='')
        select id,name,phone,isAdmin,createDate from DeviceUser where isAdmin=0 order by createDate desc
    else if(@id!='')
        select id,name,phone,isAdmin,createDate from DeviceUser where [email protected]
    else
        select id,name,phone,isAdmin,createDate from DeviceUser where [email protected]
end

--执行
exec getDeviceUser @id='', @phone=''
exec getDeviceUser @id='test guid', @phone=''
exec getDeviceUser @id='', @phone='18800000000'


--登录
create procedure getDeviceUserForLogin
    @phone nvarchar(36),
    @password nvarchar(255)
as
begin
    select id,name,phone,isAdmin,createDate from DeviceUser where [email protected] and [email protected] 
end

exec getDeviceUserForLogin @phone='18800000000',@password='123'
exec getDeviceUserForLogin @phone='18800000000',@password='123456'
exec getDeviceUserForLogin @phone='18811111111',@password='123456'

更新

create procedure updateDeviceUser
    @id nvarchar(36) ,
    @name nvarchar(36) ,
    @phone nvarchar(36) ,
    @password nvarchar(255)
as
begin
    if not exists(select 1 from DeviceUser where [email protected]) --判断用户是否存在 
        select 1 from DeviceUser where 1!=1
    else
        begin
            update DeviceUser set [email protected],[email protected],[email protected]  where [email protected]
            select id,name,phone from DeviceUser where [email protected]
        end
end
 
--执行
exec updateDeviceUser @id='guid 1',@name='test name 1',@phone='18800000000',@password='123'
exec updateDeviceUser @id='guid 2',@name='test name 2',@phone='18811111111',@password='12345678'

删除

create procedure deleteDeviceUser
    @id nvarchar(36)
as
delete from DeviceUser  where [email protected]

以上是关于Sql Server 存储过程 - 用户操作实例的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 存储过程和触发器

SQL server 2008创建触发器实例

sql server存储过程编程

sql server 存储过程如何调用存储过程

SQL Server里那些我们应该知道的系统存储过程

怎样在Sql server中创建,执行和删除存储过程