【问题标题】:SQL Server add new column to table and filled random integer in rangeSQL Server 向表中添加新列并在范围内填充随机整数
【发布时间】:2014-10-15 07:54:15
【问题描述】:

我了解如何将新列和默认 int 添加到表中。

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

如何将新列添加到表中,并用 1 到 10 之间的随机整数或随机日期填充?

编辑 - 从下面回答:

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

【问题讨论】:

标签: sql sql-server database-administration


【解决方案1】:

您可以进行更新。对于从 1 到 10 的数字,以下应该有效:

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

编辑:

Here 是在create table 语句中使用的一个示例。

【讨论】:

  • 范围内或列表外的随机日期怎么样。
  • @aggie 。 . .你会用checksum(newid())、模运算以及开始和结束日期做类似的事情。关于日期的部分比关于整数的部分要模糊得多。加上标题是关于整数而不是日期。
  • 试过这个 -> 'ALTER TABLE Cards ADD Amex int NOT NULL DEFAULT(cast(right(cast(checksum(newid()) as varchar(255)), 1) as int) + 1) ' italic_//sql 给我错误 _italic
【解决方案2】:

sql-server 中 0 到 10 的随机整数的另一种方式是:

update cards  
set Amex = CRYPT_GEN_RANDOM(2) % 11

这是一个随机月份名称的技巧:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2020-07-16
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多