Answer the question
In order to leave comments, you need to log in
How to generate a unique name randomly?
Guys, this is the task: there is a Services table (id_serv PK, title, description, cost_per_unit, id_category), the data in which is entered through a function
. The code generates random names, checks for empty lines. But the rows in the table are repeated, how to add uniqueness??? data in the table 1 million
declare @id_serv int, @id_cat int, @title nchar(15), @desc nchar(40), @cost smallmoney, @_title nchar(15), @_desc nchar(40);
set @id_serv=0
set @id_cat=1
set @title=N'abcdefghijklmnopqrstuvwxyz0123456789'
set @desc = @title + @title
set @cost=100
while @id_serv<1000000
begin
set @id_cat=Rand()*10
set @_title=SUBSTRING(@title,(Cast((RAND()*10) as int)),(Cast((RAND()*12) as int)))
while ((@_title=null or (@_title=N'% %' or @_title=N'_ ' or @_title=N' _' or @_title=N' ' or @_title=N'% ' or @_title=N' %') or @_title=''))
begin
set @_title=SUBSTRING(@title,(Cast((RAND()*10) as int)),(Cast((RAND()*12) as int)))
if((@_title!=null) or(@_title!=N'% %' or @_title!=N'_ ' or @_title!=N' _' or @_title!=N' ' or @_title!=N'% ' or @_title!=N' %') or @_title!='') break else continue
end
set @_desc=SUBSTRING(@desc,(Cast((RAND()*10) as int)),(Cast((RAND()*12) as int)))
while (@_desc=null or (@_desc=N'% %' or @_desc=N'_ ' or @_desc=N' _' or @_desc=N' ' or @_desc=N'% ' or @_desc=N' %') or @desc='')
begin
set @_desc=SUBSTRING(@desc,(Cast((RAND()*10) as int)),(Cast((RAND()*12) as int)))
if((@_desc!=null) or(@_desc!=N'% %' or @_desc!=N'_ ' or @_desc!=N' _' or @_desc!=N' ' or @_desc!=N'% ' or @_desc!=N' %') or @desc!='') break else continue
end
set @cost=(Cast((RAND()*1300) as int))
insert into Services values (@_title,@_desc,@cost,@id_cat)
set @[email protected]_serv+1
end
Answer the question
In order to leave comments, you need to log in
After you have generated a string, you need to check if there is one in the database, if so, generate a new one and so on until you get a unique string.
RAND() - it does not guarantee uniqueness and non-repeatability.
As an option to increase the chances of generating a unique string, you can play with the RAND parameter - pass as a parameter the value generated by RAND in the previous step, and remember the last value and use it the next time the procedure is called. The very first value is easiest to get from the current timestamp.
But you still need to do a check for the uniqueness of the generated string.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question