Can t-sql generate random numbers

Marksdasjkv 81 Reputation points
2022-11-22T15:42:25.45+00:00

I want to generate a set of 10 random numbers
does sql server have a method for this?

Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. NikoXu-msft 1,916 Reputation points
    2022-11-23T02:07:12.58+00:00

    Hi @Marksdasjkv ,

    Please try this query:

    ;with LoopCounter  
        as(  
            select 1 Indexer,  ABS(Cast(Cast(CRYPT_GEN_RANDOM(4) as INT) as Float)) / Cast(0x7FFFFFFF as int) RandNumber  
            union  all  
            select Indexer + 1,  ABS(Cast(Cast(CRYPT_GEN_RANDOM(4) as INT) as Float)) / Cast(0x7FFFFFFF as int)  RandNumber  
            from LoopCounter  
            where   
              Indexer < 10  
          )  
        select *  
        from LoopCounter    
        
    

    Best regards
    Niko

    ----------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2022-11-22T16:11:44.56+00:00

    Check the RAND function: https://learn.microsoft.com/en-us/sql/t-sql/functions/rand-transact-sql.

    Show details if you need something special.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.