31

I'm trying to give access to an active directory user to only one specific table. I want them to be able to insert, update, delete, etc. but only for that table. I know this command:

GRANT Insert, Select on Tablename to user

But I can't figure out how to get "domain\user" to work syntax-wise. I tried:

GRANT Insert, Select on Tablename to domain\user

But I get:

Msg 102, Level 15, State 1
Incorrect syntax near '\'.

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
bvankampen
  • 315
  • 1
  • 3
  • 6
  • Offtopic. Not a programming question. Try the DBA SE site. – Marc B Jan 03 '14 at 16:10
  • 5
    @MarcB how is a syntax issue not a programming question? – Aaron Bertrand Jan 03 '14 at 16:12
  • @aaron: in the same way that "can't make a line of text italicize in Word" isn't a programming question, unless you're trying to programatically build a Word file via COM or whatever. – Marc B Jan 03 '14 at 16:14
  • 4
    @MarcB they obviously tried `GRANT ... TO domain\user` and got `Msg 102, Level 15, State 1, Line 181 Incorrect syntax near '\'.` Are you suggesting that my answer is not a programming-related answer, but solely related to database administration? If so, I disagree 100%. – Aaron Bertrand Jan 03 '14 at 16:15
  • 1
    @MarcB your answer to aaron betrays the actual reason this should be closed --- don't just kick rubbish over to DBA.SE. – swasheck Jan 03 '14 at 16:20
  • @MarcB if you brought this problem to your DBA he would scold you quite heavily I think. – Zane Jan 03 '14 at 16:25

2 Answers2

50

Assuming you have created a user in this database associated with the AD login, e.g.

CREATE LOGIN [domain\user] FROM WINDOWS;
GO
USE your_database;
GO
CREATE USER [domain\user] FROM LOGIN [domain\user];
GO

Then you merely have to follow the same syntax. Because \ is not a standard character for an identifier, you need to escape the name with [square brackets]:

GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.Tablename TO [domain\user];
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
1

It is a good practice to create a role and add users to that role. Then grant permissions to that role.

USE database_name
GO

--1)create role 
CREATE ROLE role_name
GO

--2 create user
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'domain\user')
BEGIN
    CREATE USER [domain\user] FOR LOGIN [domain\user]
END;
GO

-- 3 Add user to the role
ALTER ROLE [role_name] ADD MEMBER [domain\user]
GO

--4 Grant permissions to the role
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.Tablename TO [role_name];
rjose
  • 557
  • 5
  • 13