SQL statements that generate 300 different random numbers and SQL statements with random numbers

Source: Internet
Author: User

SQL statements that generate 300 different random numbers and SQL statements with random numbers

-- Generate 300 random numbers with no duplicates

DECLARE @ I INT = 0; DECLARE @ j INT; DECLARE @ qnum INT = 300; -- number of random numbers generated SET NOCOUNT ONCREATE TABLE # temp_Table (num INT) WHILE (@ I <@ qnum) BEGIN SELECT @ j = cast (floor (rand () * (99999999-10000000) + 10000000) as int) IF (not exists (SELECT num FROM # temp_Table WHERE num = @ j) begin insert # temp_Table (num) VALUES (@ j) SET @ I + = 1; end endselect distinct num FROM # temp_TableDROP TABLE # temp_Table


Random numbers are randomly generated using SQL statements.

Select rand (DATEPART (mm, GETDATE () * 100000) + (DATEPART (ss, GETDATE () * 1000) + DATEPART (MS, GETDATE ())) try SQL to meet the requirements
 
Use SQL server to generate random numbers

-- Create a view
Create view myview as select re = rand ()

-- Custom function: gets a random number within a specified range.
Create function mydata (
@ A int,
@ B int)
Returns decimal (38,0)
As
Begin
Declare @ r decimal (38,0)
Select @ r = cast (re * (@ B-@ a) + @ a as decimal (38,0) from myview
Return (@ r)
End
Go

-- Call (you can specify the data range as needed)
Select user_no, dbo. mydata (1000,9999) number from table1

-- You can add a column number based on your original query. If no column is added,
-- Put the above result into a temporary table # a, and then update
-- Example:
Update table1 set number1 = a. number from # a, table1 B where a. user_no = B. user_no

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.