uiu808
uiu808

Reputation: 103

SQL Populate table with random data from a selected list of records

Is there a SQL code that could populate my table in the following matter every 3seconds? I currently am struck for quite some time. Any kind souls?

I wish to populate the id in increasing manner, position from values 1-3, the action from the list of the given list (weightlifting,shoutout,dumbbells,facewipe,tornado, muscle) and the sync from values 0-3.

enter image description here

Upvotes: 2

Views: 605

Answers (1)

downernn
downernn

Reputation: 174

Just find your database's RANDOM function. For sql-server:

INSERT INTO your_table (position, action, sync)
SELECT
   CAST(RAND() * 3 AS INT) + 1, 
   CASE CAST(RAND() * 8 AS INT) 
        WHEN 0 THEN 'Weighlifting'
        WHEN 1 THEN 'Shoutout'
        WHEN ...
   END,
   CAST(RAND() * 4 AS INT)

I'm assuming the id column is set to auto-increment and will take care of itself.

The RAND function, as most random number generator functions, will return a number in [0, 1). Multiply, add and floor the result accordingly, to get an integer in the desired range.

I suggest you consider creating a table with the possible values for the "action" column and replacing the column with a FK to that table. It will make it simpler both to populate and maintain this table.

Upvotes: 1

Related Questions