Pergunta

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

Foi útil?

Solução

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())
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top