Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random String 1

Status
Not open for further replies.

TomBarrand

Programmer
Joined
Aug 9, 2000
Messages
162
Location
GB
Is there an SQL function that you can use to generate a random string, including characters and numbers?

If not any other ideas?

Thanks
 
I do not think there is a standard function for doing this. Maybe you can think of generating a series of random numbers scale them up in the range (say 30-120 so that it covers all the characters you desire) and concatenate after converting them to single char values.
RT
 
A bit more info would be appreciated.

Thanks
 
Just a sample assuming you need a 10 character random string.


declare @rnd_str varchar(10) , @ctr int
set @ctr = 1
set @rnd_str = ''
while @ctr <= 10
begin
set @rnd_str = @rnd_str + char(33
+ convert(int , rand(datepart(ms,getdate())*1000000+datepart(ss,getdate())*10000+datepart(mi,getdate())*100+datepart(hh,getdate())+@ctr*100000000) * 100))
set @ctr = @ctr + 1
end
select @rnd_str

RT
 
I am posting this data in a query string and because the string can contain &><_- and other such characters this is causing me problems.

Any ideas on how I can limit the characters to A to Z

Thanks
 
Just modify it a little so that the output ranges from 65 to 90


declare @rnd_str varchar(10) , @ctr int
set @ctr = 1
set @rnd_str = ''
while @ctr <= 10
begin
set @rnd_str = @rnd_str + char(65
+ convert(int , rand(datepart(ms,getdate())*1000000+datepart(ss,getdate())*10000+datepart(mi,getdate())*100+datepart(hh,getdate())+@ctr*100000000) * 26))
set @ctr = @ctr + 1
end
select @rnd_str

RT
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top