8

I was wondering if there was a fairly efficient way to use T-SQL with SQL Server 2000 syntax to GRANT SELECT, INSERT, UPDATE, DELETE, on all TABLES and VIEWS for a particular database while excluding 2 or 3 of the over 100 objects. I would also like to be able to grant EXEC privileges on all Stored Procedures.

Currently I'm using the below code to change them one by one. Doing this for about 100 tables and 100 views is taking far too long and will take even longer through the GUI (Unless I'm doing that wrong too).

use [DATABASE_NAME]
GO
GRANT DELETE ON [dbo].[table_name]TO [user_name]
GO
use [DATABASE_NAME]
GO
GRANT INSERT ON [dbo].[table_name]TO [user_name]
GO
use [DATABASE_NAME]
GO
GRANT SELECT ON [dbo].[table_name]TO [user_name]
GO
use [DATABASE_NAME]
GO
GRANT UPDATE ON [dbo].[table_name]TO [user_name]
GO

How can I use T-SQL to cycle through ALL of the User Tables and Views to grant certain priveleges while excluding a couple objects?

8

Ugh, 2000.

Assuming all objects are owned by dbo, you can generate a script, e.g.:

SELECT N'GRANT INSERT, UPDATE, DELETE, SELECT ON dbo.' + QUOTENAME(name)
  + N' TO [user];'
FROM sysobjects WHERE type IN (N'U', N'V');

SELECT N'GRANT EXECUTE ON dbo.' + QUOTENAME(name)
  + N' TO [user];'
FROM sysobjects WHERE type = N'P';

Now you can copy and paste the output in case you want to exclude any entries or validate. If you just want to blindly execute, you can instead do this, but it relies on the content of any individual set of commands being < 4K:

DECLARE @sql NVARCHAR(4000) = N'';

SELECT @sql = @sql + N'GRANT INSERT, UPDATE, DELETE, SELECT ON dbo.' + QUOTENAME(name)
  + N' TO [user];'
FROM sysobjects WHERE type = N'U';

EXEC sp_executesql @sql;

SET @sql = N'';

SELECT @sql = @sql + N'GRANT INSERT, UPDATE, DELETE, SELECT ON dbo.' + QUOTENAME(name)
  + N' TO [user];'
FROM sysobjects WHERE type = N'V';

EXEC sp_executesql @sql;

SET @sql = N'';

SELECT @sql = @sql + N'GRANT EXECUTE ON dbo.' + QUOTENAME(name)
  + N' TO [user];'
FROM sysobjects WHERE type = N'P';

EXEC sp_executesql @sql;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.