Permissions for truncating a table

2019-02-16 04:16发布

What permission do I need to GRANT a user, in MSSQL, in order to be able to truncate a table?

I'm trying to grant the minimal set of permissions, but I can't use DELETE, because the table is very large, and I want the operation to be quick.

5条回答
再贱就再见
2楼-- · 2019-02-16 04:19

You need the ALTER permission: see the Permissions section here.

Note that you can also use a stored procedure with EXECUTE AS, so that the user running the stored procedure does not need to even be granted the ALTER permission.

查看更多
爷、活的狠高调
3楼-- · 2019-02-16 04:19

The minimum permission required is ALTER on table_name. TRUNCATE TABLE permissions default to the table owner, members of the sysadmin fixed server role, and the db_owner and db_ddladmin fixed database roles, and are not transferable. However, you can incorporate the TRUNCATE TABLE statement within a module, such as a stored procedure, and grant appropriate permissions to the module using the EXECUTE AS clause. For more information, see Using EXECUTE AS to Create Custom Permission Sets.

Source

查看更多
Evening l夕情丶
4楼-- · 2019-02-16 04:28

You can create a stored procedure with execute as owner to only one table or a store procedure to any table:

CREATE PROCEDURE [dbo].[spTruncate]
    @nameTable varchar(60)  
    WITH EXECUTE AS OWNER
    AS

SET NOCOUNT OFF;
DECLARE @QUERY NVARCHAR(200);

SET @QUERY = N'TRUNCATE TABLE ' + @nameTable + ';'

EXECUTE sp_executesql @QUERY;
查看更多
我命由我不由天
5楼-- · 2019-02-16 04:35

You can create a stored procedure with execute as owner:

create procedure dbo.TruncTable
with execute as owner
as
truncate table TheTable
go

Then grant execution permissions to whoever needs to truncate that table:

grant execute on TruncTable to TheUser

Now TheUser can truncate the table like:

exec dbo.TruncTable
查看更多
太酷不给撩
6楼-- · 2019-02-16 04:45

Don't GRANT, hide...

CREATE TRIGGER TRG_MyTable_Foo 
WITH EXECUTE AS OWNER
INSTEAD OF DELETE
AS
IF CONTEXT_INFO() = 0x9999
BEGIN
    TRUNCATE TABLE MyTable
    SET CONTEXT_INFO 0x00
END
GO

SET CONTEXT_INFO 0x9999
DELETE MyTable WHERE 1=0

SET CONTEXT_INFO may be is without any doubt better to separate a normal DELETE from a TRUNCATE TABLE

I haven't tried this...

Edit: changed to use SET CONTEXT_INFO.

查看更多
登录 后发表回答