Click here to Skip to main content
15,917,991 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to generate random number using character between A-F and 0-9 up to 30 char length in SQL Server?

where random number are unique?
Posted
Updated 1-Aug-12 1:36am
v2
Comments
Kenneth Haugland 1-Aug-12 7:41am    
Why dont you let the SQL server handle that? I mean set the SQL server to autogenerate the ID column

Hi,
Try this:
SQL
CREATE procedure dbo.GenerateRandomString (
 @useNumbers bit,
 @useUpperCase bit,
 @string varchar(100) OUT
)
As
Begin
	DECLARE @charactersToUse VARCHAR(8), @stringLength INT
	SET @charactersToUse='ABCDEF'
	SET @stringLength=8
if @stringLength <= 0
 raiserror('Cannot generate a random string of zero length.',16,1)

declare @characters varchar(100)
declare @count int

set @characters = ''

if @useNumbers = 1
begin
 -- load up numbers 0 – 9
 set @count = 48
 while @count <=57
 begin
     set @characters = @characters + Cast(CHAR(@count) as char(1))
     set @count = @count + 1
 end
end

if @useUpperCase = 1
begin
 -- load up lowercase letters a – z
 set @count = 97
 while @count <=122
 begin
     set @characters = @characters + Cast(CHAR(@count) as char(1))
     set @count = @count + 1
 end
end

set @count = 0
set @string = ''

-- If you specify a character set to use, the bit flags get ignored.
if Len(@charactersToUse) > 0
begin
 while charindex(@charactersToUse,' ') > 0
 begin
  set @charactersToUse = replace(@charactersToUse,' ','')
 end

 if Len(@charactersToUse) = 0
  raiserror('Cannot use an empty character set.',16,1)

 while @count <= @stringLength
 begin
    
set @string = @string +
SUBSTRING(@charactersToUse,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as
int)%LEN(@charactersToUse)+1,1)
     set @count = @count + 1
 end
end
else
begin
 while @count <= @stringLength
 begin
    
set @string = @string +
SUBSTRING(@characters,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as
int)%LEN(@characters)+1,1)
     set @count = @count + 1
 end
end

end
GO


All the best.
--Amit
 
Share this answer
 
v2
Comments
Kamalkant(kk) 1-Aug-12 8:03am    
Thanks Amit, but I need in SQL SERVER
_Amy 1-Aug-12 8:16am    
Try the updated answer..
try this.


SQL
DECLARE @randstring AS char(30)
SELECT @randstring =replace(cast(newid() AS varchar(36))+cast(newid() AS varchar(36)),'-','')
SELECT @randstring 
 
Share this answer
 
v2
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=164015[^]

Check this link... It may hepls you
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900