1

I have a column which I want to update randomly with a value that is either 1, 2, 3, 4, 5 or 6. Can anyone help please?

1
  • 1
    Do you care about distribution of the "random" values? i.e. do you need a roughly equal number of rows updated with each value from 1 to 6? If you are doing this to mask existing values for use in testing, it may be important to approximately retain the existing frequency distribution. If you are adding a new column where you want the values to be randomly assigned in the range of 1 to 6, you could use a default constraint to ensure future values are randomly assigned. You may find it useful to add detail to your question, in accordance with the directions in minimal reproducible example.
    – Hannah Vernon
    Commented Nov 16, 2023 at 18:29

2 Answers 2

1

+1

This should get you what you need.

CREATE TABLE
    #rando
(
    id bigint NOT NULL 
      PRIMARY KEY
      IDENTITY,
    rando tinyint
);

INSERT
    #rando WITH (TABLOCK)
(
    rando
)
SELECT TOP (1000)
    rando = 0
FROM sys.messages AS m;

UPDATE r
 SET r.rando = ABS(CHECKSUM(NEWID()) % 6) + 1
FROM #rando AS r;

SELECT
    r.*
FROM #rando AS r
ORDER BY
    r.id
0
1

This Link has some detailed information. In your case, you can try leveraging the RAND() function, and CROSS APPLY as well as NewId() to generate a random value. Using RAND() by itself will apply the same random value to all values in the update statement.

Example SQL:

/**********************************************************************************************************************
** Create sample Table
**********************************************************************************************************************/
DROP TABLE IF EXISTS #Foobar;
CREATE TABLE #Foobar
(
    StaticVal nvarchar(10),
    RandomValue int
);

INSERT INTO #Foobar
(
    StaticVal
)
VALUES
('Hello'),
('World'),
('Sample'),
('Data');

/**********************************************************************************************************************
** Updating Existing Table
**********************************************************************************************************************/
UPDATE
    F
SET
    F.RandomValue = R.Val
FROM #Foobar AS F
CROSS APPLY
(SELECT Val = ABS (CHECKSUM (NEWID ())) % 6 +1) AS R;


/**********************************************************************************************************************
** Select From Table
**********************************************************************************************************************/
SELECT * FROM #Foobar AS F;

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.