在SQL SERVER中列許可權(Column Permissions)其實真沒有什麼好說的,但是好多人對這個都不甚瞭解,已經被人問了幾次了,所以還是在這裡介紹一下,很多人都會問,我能否單獨對錶的某列授權給某個用戶? 答案是可以,我們可以對錶中的列授予SELECT、UPDATE許可權,我們結合下麵的簡單... ...
在SQL SERVER中列許可權(Column Permissions)其實真沒有什麼好說的,但是好多人對這個都不甚瞭解,已經被人問了幾次了,所以還是在這裡介紹一下,很多人都會問,我能否單獨對錶的某列授權給某個用戶? 答案是可以,我們可以對錶中的列授予SELECT、UPDATE許可權,我們結合下麵的簡單案例來闡述一下可能效果更好。
案例1: 在AdventureWorks2014中,登錄名UserA 只能有許可權查詢[Person].[Person]裡面的BusinessEntityID, NationalIDNumber, LoginID三個欄位許可權,不能查詢其它欄位
USE [master]
GO
CREATE LOGIN [UserA] WITH PASSWORD=N'UserA', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
USE [AdventureWorks2014]
GO
CREATE USER [UserA] FOR LOGIN [UserA]
GO
給用戶授予相關列的查詢許可權(SELECT)
GRANT SELECT(BusinessEntityID, NationalIDNumber, LoginID) ON [HumanResources].[Employee] TO [UserA]
此時你可以用下麵SQL查看授予UserA的許可權:
SELECT dp.grantee_principal_id ,
P.name AS UName ,
dp.permission_name ,
C.name ,
OBJECT_NAME(O.object_id) AS TabName
FROM sys.database_permissions dp
INNER JOIN sys.objects O ON dp.major_id = O.object_id
INNER JOIN sys.columns C ON C.object_id = O.object_id
AND C.column_id = dp.minor_id
INNER JOIN sys.database_principals P ON P.principal_id = dp.grantee_principal_id;
以用戶UserA登錄,如下所示,如果查詢語句使用BusinessEntityID, NationalIDNumber, LoginID欄位之外的其它欄位,就會出現類似下麵錯誤,當然也不能使用SELECT *之類的查詢語句。
Msg 230, Level 14, State 1, Line 8
The SELECT permission was denied on the column 'JobTitle' of the object 'Employee', database 'AdventureWorks2014', schema 'HumanResources'.
另外,也可以只授權用戶更新某個列,例如對於登錄名UserB,只允許其修改Person.Address的AddressLine1,AddressLine2兩個欄位,其它欄位不許修改。
GRANT UPDATE(AddressLine1,AddressLine2) ON [Person].[Address] TO UserB;
SELECT dp.grantee_principal_id ,
P.name AS UName ,
dp.permission_name ,
C.name ,
OBJECT_NAME(O.object_id) AS TabName
FROM sys.database_permissions dp
INNER JOIN sys.objects O ON dp.major_id = O.object_id
INNER JOIN sys.columns C ON C.object_id = O.object_id
AND C.column_id = dp.minor_id
INNER JOIN sys.database_principals P ON P.principal_id = dp.grantee_principal_id
WHERE P.name='UserB'
另外,關於DELETE、INSERT許可權,這個是沒有所謂的列許可權(Column Permissions)的,其實從邏輯上想想,你也能明白,這這兩者對應的最小單位為一條記錄,所以根本不能再細化到列級別了。
Msg 1020, Level 15, State 1, Line 36
Sub-entity lists (such as column or security expressions) cannot be specified for entity-level permissions.