Set Limit for a Table Rows In SQL

前端 未结 4 616
感情败类
感情败类 2020-12-03 12:57

I want to set the limit for my table\'s rows. How can I do it?

For example 50 rows in my table.

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 13:28

    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 
    

提交回复
热议问题