【问题标题】:Set a limit on the number of rows of a SQL Server table [duplicate]设置 SQL Server 表的行数限制 [重复]
【发布时间】:2017-05-05 14:58:57
【问题描述】:

我想设置我创建的 SQL Server 表可以拥有的最大行数。问题是我有一个程序不断在我的数据表中写入新数据,但我只需要每列存储一个值。所以我想将此数据表的最大可能行数设置为一个。有谁知道如何做到这一点?

否则,由于到目前为止我还没有找到这样做的可能性,我还考虑过重写我的代码并使用 SQL UPDATE 语句。

我不太确定什么会更好。

【问题讨论】:

  • 我认为没有任何内置方法可以限制表的行数。你必须自己处理这个,例如在AFTER INSERT 触发器或其他东西中
  • 假设您的行限制类似于 1000... 一旦您运行插入,那么您可以运行删除语句来删除您需要的行数,以便使用 CTE 和ROW_NUMBER 以及其他方式
  • 我认为马克的建议是你最好的选择。如果您的能够设置最大值,那么您将面临破坏写入数据库的应用程序的风险。
  • 您可以使用permissions。您可以将应用程序及其用户限制为仅更新。这种方法需要您重构应用程序。
  • @marc_s 我想这将是要走的路......

标签: sql sql-server ssms


【解决方案1】:

向您的表中添加一个标识列并将其限制在您的限制范围内。

create table dbo.MyTable (MyColumn varchar(10), i int identity(1,1) check(i <= 5));

insert into dbo.MyTable 
    select 'one' union 
    select 'two' union 
    select 'three' union 
    select 'four' union
    select 'five';


insert into dbo.MyTable 
    select 'nope';

Msg 547, Level 16, State 0, Line 7
The INSERT statement conflicted with the CHECK constraint 

如果真的只有一行,也许是这样的?

create table dbo.MyTable (MyColumn varchar(10), Limited bit not null default(1) unique);

insert into dbo.MyTable (MyColumn)
    select 'only one';

insert into dbo.MyTable (MyColumn)
    select 'nope';

【讨论】:

  • 那只会限制列的数量不是吗?
  • 不,它限制了行。您可以随意在我的示例中添加其他列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 2012-03-04
  • 2020-10-07
  • 1970-01-01
相关资源
最近更新 更多