转载自:SQL SERVER 使用存储过程编写重置密码以及还原密码的存储过程
需求
正式环境中系统用户密码被修改,若要用指定账户登录,在无法联系到用户获取密码的情况下,只能先将密码重置为默认密码,登录上系统后,再修改回来。此种方式直接使用sql修改很繁琐。
解决方式
使用存储过程方式,简化操作
存储过程实现
SQL
CREATE PROCEDURE [dbo].[updatePassword]
(
@userId VARCHAR(1000),
@updateOrRevert int --1重置密码 2还原密码
)
WITH EXECUTE AS 'dbo'
AS
BEGIN
Declare @userExit int;--用户记录是否存在
Declare @defaultPassword VARCHAR(1000);--默认密码
Declare @oldPassword VARCHAR(1000);--旧密码
select @defaultPassword='371D623D73023f321650223216010e15';
--判断表不存在时
IF NOT EXISTS(Select 1 From Sysobjects Where Name='temp_user_password')
--创建临时密码表
create table temp_user_password
(
[userId] [varchar](100) NOT NULL,
[oldPassword] [varchar](1000) NOT NULL
);
if(@userId ='')
begin
print('请输入用户id')
return;
end
if(@updateOrRevert ='')
begin
print('请输入类型 1重置密码 2还原密码')
return;
end
--重置密码
if(@updateOrRevert = 1)
begin
--用户id参数不为空字符串时
if(@userId != '' )
begin
--根据userId查询旧密码
Select @oldPassword=password from user_info where user_id=@userId;
--判断临时密码表里面是否有该用户的记录
select @userExit=1 from temp_user_password where userId=@userId;
--如果有记录
if(@userExit=1)
begin
--修改旧密码记录
update temp_user_password set oldPassword=@oldPassword where userId=@userId;
end
else
begin
--没有记录,新增旧密码记录
insert into temp_user_password (userId,oldPassword) values (@userId,@oldPassword);
end
--更新用户表该用户id的密码,重置为默认密码
update user_info set password=@defaultPassword where user_id=@userId;
end
end
--还原密码
if(@updateOrRevert = 2)
begin
--用户id参数不为空字符串时
if(@userId != '' )
begin
--从临时表查询旧密码
select @oldPassword=oldPassword from temp_user_password where userId=@userId;
--旧密码不为空
if(@oldPassword !='')
begin
--给该用户,重设旧密码
update user_info set password=@oldPassword where user_id=@userId;
end
end
end
END
SQLSERVER 存储过程基本语法参考: