I want to set the limit for my table\'s rows. How can I do it?
For example 50 rows in my table.
What you want is having a INSTEAD OF INSERT
trigger that checks the # of current rows. If already 50, you will raise an error by using RAISERROR. If not, you just insert
the record.
Warning! Untested code ahead. It might contain typos or slight syntax errors. The code is supposed to show you the concepts involved. Tweak and adjust to your needs accordingly.
Like this:
CREATE TRIGGER checktablelimit
ON yourtable
INSTEAD OF INSERT
AS
DECLARE @currentCount INT
SELECT @currentCount = COUNT(*)
FROM yourtabletolimit
IF @currentCount = 50
BEGIN
RAISERROR ('Table already has 50 records',
11,
1);
END
ELSE
BEGIN
INSERT INTO yourtable
(field1,
field2,
field3)
SELECT field1,
field2,
field3
FROM inserted
END
GO