34,590
社区成员
发帖
与我相关
我的任务
分享
-- 假设有账号 a, 用户组 aa, 并且账号 a 是用户组 aa 的成员
/*-- 如果是SQL Server服务器本机测试,可以用本机 Windows 账号,本机测试帐号可以参考如下方式在管理员提示符下完成
--- 使用本机 Windows 帐号测试,则下面 SQL 中的 域名 修改为本机 计算机名
net localgroup aa /add
net user a '!2ab.1234' /add
net localgroup aa a /add
net user a
--*/
-- 测试表
use tempdb;
go
create table t1(id int);
create table t2(id int);
go
-- 为账号 a 授权,仅能查询 t1
create login [域名\a] from windows;
create user a for login [域名\a];
grant select on t1 to a;
go
-- 以账号 a 的身份执行查询
execute as login = '域名\a';
go
select * from t1;
select * from t2; -- 无权限,所以这个查询报错
go
revert;
go
-- 为组 aa 授权权限 t2
create login [域名\aa] from windows;
create user aa for login [域名\aa];
grant select on t2 to aa;
go
-- 以账号 a 的身份执行查询
execute as login = '域名\a';
go
select * from t1;
select * from t2; -- 成功查询。虽然没有为账号 a 授权查询此表,但它所属的组有权限,所以仍然能查询
go
revert;
go
-- 删除测试
drop user aa;
drop user a;
drop login [域名\aa];
drop login [域名\a];
drop table t1,t2