How to make a table Read Only in SQL Server?

前端 未结 3 1093
天涯浪人
天涯浪人 2020-12-08 08:02

I am updating some set of records in that table, after that I need to make this table read only.

So how to make a table Read Only in SQL Server?

相关标签:
3条回答
  • 2020-12-08 08:21

    A simple alternative that would block update and insert on a specific table but still allowing delete:

    ALTER TABLE mytable WITH NOCHECK ADD CONSTRAINT chk_read_only CHECK( 1 = 0 )
    

    Be aware: this avoids INSERTs and UPDATEs, but allows DELETEs.

    If you really need a table to be truly read only you could also either:

    a) put it in its own database or
    b) put it on a file group and mark that read only, here’s how:

    USE [master]
    
    GO
    
    ALTER DATABASE [csvtosp] ADD FILEGROUP [READONLYTABLES]
    
    GO
    
    ALTER DATABASE [csvtosp] ADD FILE ( NAME = N'mydb_readonly_tables', FILENAME = N'G:\SQL2005DATA\mydb_readonly_tables.ndf' , SIZE = 3072KB , FILEGROWTH = 1024KB ) TO FILEGROUP [READONLYTABLES]
    
    GO
    
    USE csvtosp
    
    GO
    
    DROP TABLE mytable
    
    CREATE TABLE mytable (
    
        somedata    char(8000) not null
    
    ) ON READONLYTABLES
    
    GO
    

    For more details on this subject, go here:

    How to make a table Read Only in SQL Server

    0 讨论(0)
  • 2020-12-08 08:22

    If you want it as read only to the general public, but still want to be able to edit the table at a later date, you may want to consider creating multiple users for the database and granting different permissions to that database - ideally you should be doing this anyway and not allow the general public access to alter table, truncate etc.

    0 讨论(0)
  • 2020-12-08 08:27
    1. Trigger with rollback trans
    2. Read only filegroup
    3. Don't grant insert/update/delete permissions

    Number 3 is probably best practice. For example, if your connection is db_owner for example then the trigger can be disabled the trigger or move the table to a different filegroup anyway.

    0 讨论(0)
提交回复
热议问题