Permissions for truncating a table

别说谁变了你拦得住时间么 提交于 2019-12-01 02:39:21
Shahar Mosek

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.

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

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

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.

user3854427

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!