我想在我的数据库表中添加一个约束,以便字符串" username"只能输入特定列最多10次。这可能吗?
我正在使用ms sql server。
答案 0 :(得分:6)
您可以使用AFTER
触发器UPDATE/INSERT
:
<强> SQLFiddleDEMO 强>
CREATE TABLE tab(col NVARCHAR(100));
CREATE TRIGGER trg_tab
ON tab
AFTER INSERT, UPDATE
AS
IF (SELECT COUNT(*) FROM tab WHERE col = 'username') > 10
ROLLBACK;
INSERT INTO tab(col)
VALUES ('username'), ('username'), ('username'), ('username'),
('username'), ('username'), ('username'), ('username'),
('username'),('username');
INSERT INTO tab(col)
VALUES ('username');
/* The transaction ended in the trigger. The batch has been aborted. */
或使用SCALAR FUNCTION
和CHECK
约束:
<强> SQLFiddleDemo2 强>
CREATE TABLE tab(col NVARCHAR(100));
CREATE FUNCTION dbo.CheckFunction()
RETURNS INT
AS
BEGIN
RETURN (SELECT COUNT(*) FROM tab WHERE col = 'username')
END;
ALTER TABLE tab
ADD CONSTRAINT chkRowCount CHECK (dbo.CheckFunction() <= 10 );
INSERT INTO tab(col)
VALUES ('username'), ('username'), ('username'), ('username'),
('username'), ('username'), ('username'), ('username'),
('username'),('username');
INSERT INTO tab(col)
VALUES ('username');
/* The INSERT statement conflicted with the CHECK constraint "chkRowCount".
The conflict occurred in database "db_6_34d5e", table "dbo.tab". */
答案 1 :(得分:2)
在表格上创建AFTER INSERT
触发器。像这样的事情
create trigger LimitTable
on YourTableToLimit
after insert
as
declare @tableCount int
select @tableCount = Count(*)
from YourTableToLimit
if @tableCount > 50
begin
rollback
end
go