SQL 游标、函数生成随机强密码批量修改
CREATE FUNCTION GetPwd(@count int) RETURNS varchar(8000) AS begin declare @temp table(id int identity primary key,pwd char(1)) declare @i int,@sql varchar(1000) set @i=0 while @i<10 begin insert into @temp select ltrim(@i) set @i=@i+1 end set @i=65 while @i<91 begin insert into @temp select char(ltrim(@i)) set @i=@i+1 end set @i=97 while @i<123 begin insert into @temp select char(ltrim(@i)) set @i=@i+1 end insert into @temp select '!' union all select '@' union all select '#' union all select '$' union all select '%' union all select '^' union all select '&' union all select '*' union all select '(' union all select '_' union all select '+' union all select '~' declare @s varchar(8000) set @i=0 while @i<@count begin select top 1 @s=isnull(@s,'')+pwd from @temp order by (select * from V_getnewid) set @i=@i+1 end return @s end go CREATE view V_getnewid AS select newid() AS rand_id go declare @sPassword varchar(200),@Id varchar(50) DECLARE My_Cursor CURSOR --定义游标 FOR (select Id from tb_User) --查出需要的集合放到游标中 OPEN My_Cursor; --打开游标 FETCH NEXT FROM My_Cursor into @Id; --读取第一行数据 WHILE @@FETCH_STATUS = 0 BEGIN set @sPassword=dbo.GetPwd(8); UPDATE tb_User SET sPassWord = UPPER(RIGHT(sys.fn_varbintohexstr(HASHBYTES('MD5',@sPassword)),32)), Pw=@sPassword where Id=@Id FETCH NEXT FROM My_Cursor into @Id; --读取下一行数据 END CLOSE My_Cursor; --关闭游标 DEALLOCATE My_Cursor; --释放游标 GO select Pw,* from tb_User