랜덤 캐릭터 생성하기
- Version : SQL Server 2005, 2008, 2008R2, 2012, 2014
무작위로 패스워드를 생성해야 하거나 쿠폰번호 등을 생성해야 할 때 일정한 범위내에서 랜덤한 문자열을 생성하는 코드를 만들어 본다.
랜덤한 문자열을 만들기 위해서 이전에 다루었던 RAND BETWEEN 함수를 사용하여 일정한 범위 내에서 난수를 발생 시킬 수 있도록 한다.
- RANDBETWEEN 함수 만들기 : http://sqlmvp.kr/220082013377
RAND BETWEEN 생성
create view vRandomNumber as select rand() as RandomNumber go
create function randbetween(@bottom int, @top int) returns int as begin return (select cast(round((@top-@bottom)* RandomNumber + @bottom,0) as integer) from vRandomNumber) end go |
RANDBWTWEEN을 활용한 랜덤 캐릭터 생성
CREATE FUNCTION dbo.GeneratePassword () RETURNS varchar(10) AS BEGIN DECLARE @randInt int; DECLARE @NewCharacter varchar(1); DECLARE @NewPassword varchar(10); SET @NewPassword='';
--6 random characters WHILE (LEN(@NewPassword) <6) BEGIN select @randInt=dbo.randbetween(48,122) -- 0-9 < = > ? @ A-Z [ \ ] a-z IF @randInt<=57 OR (@randInt>=60 AND @randInt<=93) OR (@randInt>=97 AND @randInt<=122) Begin select @NewCharacter=CHAR(@randInt) select @NewPassword=CONCAT(@NewPassword, @NewCharacter) END END
--Ensure a lowercase select @NewCharacter=CHAR(dbo.randbetween(97,122)) select @NewPassword=CONCAT(@NewPassword, @NewCharacter)
--Ensure an upper case select @NewCharacter=CHAR(dbo.randbetween(65,90)) select @NewPassword=CONCAT(@NewPassword, @NewCharacter)
--Ensure a number select @NewCharacter=CHAR(dbo.randbetween(48,57)) select @NewPassword=CONCAT(@NewPassword, @NewCharacter)
--Ensure a symbol WHILE (LEN(@NewPassword) <10) BEGIN select @randInt=dbo.randbetween(33,64) -- ! # $ % & < = > ? @ IF @randInt=33 OR (@randInt>=35 AND @randInt<=38) OR (@randInt>=60 AND @randInt<=64) Begin select @NewCharacter=CHAR(@randInt) select @NewPassword=CONCAT(@NewPassword, @NewCharacter) END END
RETURN(@NewPassword); END; GO |
랜덤하게 생성되는 캐릭터를 확인한다.
SELECT dbo.GeneratePassword() AS 'NewPassword'; SELECT dbo.GeneratePassword() AS 'NewPassword'; SELECT dbo.GeneratePassword() AS 'NewPassword'; |
강성욱 / jevida@naver.com
Microsoft SQL Server MVP
Blog : http://sqlmvp.kr
Facebook : http://facebook.com/sqlmvp