Looking for SQL constraint: SELECT COUNT(*) from tBoss < 2

亡梦爱人 提交于 2019-12-11 20:55:29

问题


I'd like to limit the entries in a table. Let's say in table tBoss. Is there a SQL constraint that checks how many tuples are currently in the table? Like

SELECT COUNT(*) from tBoss < 2

Firebird says:

Invalid token. Dynamic SQL Error. SQL error code = -104. Token unknown - line 3, column 8. SELECT.

Thanks. Norbert


回答1:


Does your database have triggers? If so, Add a trigger that rolls back any insert that would add more than 2 rows...

Create Trigger MyTrigName
For Insert On tBoss
As
    If (Select Count(*) From tBoss) > 2
       RollBack Transaction

but to answer your question directly, the predicate you want is to just put the select subquery inside parentheses. like this ...

  [First part of sql statement ]
  Where (SELECT COUNT(*) from tBoss) < 2



回答2:


You could do this with a check constraint and a scalar function. Here's how I built a sample.

First, create a table:

CREATE TABLE MyTable
 (
   MyTableId  int           not null  identity(1,1)
  ,MyName     varchar(100)  not null
 )

Then create a function for that table. (You could maybe add the row count limit as a parameters if you want more flexibility.)

CREATE FUNCTION dbo.MyTableRowCount()
RETURNS int
AS
 BEGIN
    DECLARE @HowMany int

    SELECT @HowMany = count(*)
      from MyTable
    RETURN @HowMany
 END

Now add a check constraint using this function to the table

ALTER TABLE MyTable
 add constraint CK_MyTable__TwoRowsMax
  check (dbo.MyTableRowCount() < 3)

And test it:

INSERT MyTable (MyName) values ('Row one')
INSERT MyTable (MyName) values ('Row two')
INSERT MyTable (MyName) values ('Row three')
INSERT MyTable (MyName) values ('Row four')

A disadvantage is that every time you insert to the table, you have to run the function and perform a table scan... but so what, the table (with clustered index) occupies two pages max. The real disadvantage is that it looks kind of goofy... but everything looks goofy when you don't understand why it has to be that way.

(The trigger solution would work, but I like to avoid triggers whenever possible.)




回答3:


To find multiples in a database your best bet is a sub-query for example: (Note I am assuming you are looking to find duplicated rows of some sort)

SELECT id FROM tBoss WHERE id IN ( SELECT id FROM tBoss GROUP BY id HAVING count(*) > 1 )

where id is the possibly duplicated column




回答4:


SELECT COUNT(*) FROM tBoss WHERE someField < 2 GROUP BY someUniqueField


来源:https://stackoverflow.com/questions/1631070/looking-for-sql-constraint-select-count-from-tboss-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!