这个问题在这里已经有了答案:
Set Limit for a Table Rows In SQL
(4 个回答)
4年前关闭。
我想设置我创建的 SQL Server 表可以拥有的最大行数。问题是我有一个程序会不断在我的数据表中写入新数据,但我只需要每列存储一个值。所以我想将此数据表的最大可能行数设置为一。有谁知道如何做到这一点?
否则,由于到目前为止我还没有找到这样做的可能性,我还考虑过重写我的代码并使用 SQL UPDATE 语句。
我不太确定什么会更好。
最佳答案
向您的表中添加一个标识列并将其限制为您的限制。
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';
关于sql - 对 SQL Server 表的行数设置限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43808143/