简体   繁体   中英

Generate numbers in range — SQL

I have to generate random values in a range with case statements.

For example, we have a table of products as follows:

Product
TV
Refrigerator
Laptop

Now I need to generate COSTPRICE, SALEPRICE for testing purpose. Since the price of the products varies from one to another, I need to generate values in a range. For example, if the value is TV, then generate values between 1000 to 1100 OR if the value is Refrigerator, then generate values between 800-1000 and so on.

Any ideas/functions how I could approach this using SQL? I am aware of the function RAND(), but I cannot generate range values with this.

Please help me at least to push myself to find a solution. Thanks

So are you basically looking for something like this:

SELECT CASE WHEN Product='TV' THEN (1000 + CONVERT(INT, (101)*RAND())) ELSE CASE WHEN Product='Refrigerator' THEN (800 + CONVERT(INT, (201)*RAND())) ELSE 0 END END FROM ProductTable

The idea is pretty simple when it comes to random number between @min & @max. See below:

SELECT @min + CONVERT(INT, (@Max-@min+1)*RAND())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM