1

I understand how to add a new column and default int to a table.

ALTER TABLE Cards
ADD Amex int NOT NULL DEFAULT(1) // how can I add a random number (between 1, to 10) or random date (jan to feb etc)?
GO

How do I add a new column into a table, and fill it with a random integer between 1 and 10, or a random date?

Edit - Answer from below:

Create table cards (
  Amex int NOT NULL DEFAULT (cast(right(cast(checksum(newid()) as varchar(255)), 1) as int) + 1)
);
1

2 Answers 2

4

You can do an update. For a number from 1 to 10, the following should work:

update cards
    set Amex = cast(right(cast(checksum(newid()) as varchar(255)), 1) as int) + 1

EDIT:

Here is an example of this being used in a create table statement.

3
  • What about random dates in a range or out of a list.
    – aggie
    Oct 15, 2014 at 7:59
  • @aggie . . . You would do something similar with checksum(newid()), modulo arithmetic, and start and end dates. The part of the question about dates is much vaguer than the part about integers; plus the title is about integers and not dates. Oct 15, 2014 at 16:56
  • tried this -> 'ALTER TABLE Cards ADD Amex int NOT NULL DEFAULT(cast(right(cast(checksum(newid()) as varchar(255)), 1) as int) + 1)' italic_//sql is giving me errors _italic
    – aggie
    Oct 15, 2014 at 17:08
1

another way for random integer from 0 to 10 in sql-server is:

update cards  
set Amex = CRYPT_GEN_RANDOM(2) % 11

here is a trick for a random month names:

= DATENAME(month, DATEADD(month, (CRYPT_GEN_RANDOM(2) % 13), getdate()))

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.