应用程序角色是特殊的数据库角色,用于允许用户通过特定应用程序获取特定数据。应用程序角色不包含任何成员,而且在使用它们之前要在当前连接中将它们激活。激活一个应用程序角色后,当前连接将丧失它所具备的特定用户权限,只获得应用程序角色所拥有的权限。
2.5.1 创建应用程序角色
可以使用CREATE APPLICATION ROLE语句来创建一个应用程序角色。
-- Change the connection context to the database AdventureWorks.
USE AdventureWorks
GO
-- Create the Application role FinancialRole
-- in the current database
CREATE APPLICATION ROLE FinancialRole
WITH PASSWORD = 'Pt86Yu$$R3';
2.5.2 使用应用程序角色
应用程序角色在使用之前必须激活。可以通过执行sp_setapprole系统存储过程来激活应用程序角色。在连接关闭或执行系统存储过程sp_unsetapprole之前,被激活的应用程序角色都将保持激活状态。虽然应用程序角色旨在由客户的应用程序使用,但我们同样可以在即筛T-SQL批处理中使用它们。以下存储过程演示了如何激活应用程序角色FinancialRole并解除这个操作。
-- Change the connection context to the database AdventureWorks.
USE AdventureWorks;
GO
-- Declare a variable to hold the connection context.
-- We will use the connection context later
-- so that when the application role is deactivated
-- the connection recovers its original context.
DECLARE @context varbinary (8000); //声明一个变量
-- Activate the application role
-- and store the current connection context
EXECUTE sp_setapprole 'FinancialRole','Pt86Yu$$R3', //应用程序角色和密码
@fCreateCookie = true,
@cookie = @context OUTPUT;
-- Verify that the user’s context has been replaced
-- by the application role context.
SELECT CURRENT_USER;
-- Deactivate the application role,
-- recovering the previous connection context.
EXECUTE sp_unsetapprole @context;
GO
-- Verify that the user’s original connection context
-- has been recovered.
SELECT CURRENT_USER;
GO
2.5.3 删除应用程序角色
如果需要删除应用程序角色,可以使用DROP APPLICATION ROLE语句。如下所示:
-- Change the connection context to the database AdventureWorks.
USE AdventureWorks;
GO
-- Drop the application role FinancialRole
-- from the current database
DROP APPLICATION ROLE FinancialRole