EXECUTE AS
的替代方案是模塊簽名。這需要比EXECUTE AS
更多的配置,但具有保留呼叫者身份而不授予用戶直接權限的優點,並且可以擴展用於跨數據庫訪問。
下面是一個示例腳本,摘自Erland Sommarskog關於Giving Permissions through Stored Procedures的優秀文章。
CREATE TABLE dbo.testtbl (a int NOT NULL,
b int NOT NULL);
INSERT dbo.testtbl (a, b) VALUES (47, 11);
GO
CREATE PROCEDURE example_sp AS
SELECT SYSTEM_USER, USER, name, type, usage FROM sys.user_token;
EXEC ('SELECT a, b FROM testtbl');
GO
-- Create the certificate.
CREATE CERTIFICATE examplecert
ENCRYPTION BY PASSWORD = 'All you need is love'
WITH SUBJECT = 'Certificate for example_sp',
START_DATE = '20020101', EXPIRY_DATE = '20200101';
GO
-- Create the certificate user and give it rights to access the test table.
CREATE USER examplecertuser FROM CERTIFICATE examplecert;
GRANT SELECT ON dbo.testtbl TO examplecertuser;
GO
-- Sign the procedure.
ADD SIGNATURE TO dbo.example_sp BY CERTIFICATE examplecert
WITH PASSWORD = 'All you need is love';
GO
--users need proc execute permissions but not table permissions
GRANT EXECUTE ON dbo.example_sp TO YourUserOrRole;
GO
我有執行權限的proc。 proc裏面有插入查詢和其他許多查詢。 其他查詢很好,但當我嘗試運行動態查詢(插入一個):通過:exec(@insertQuery)...我得到錯誤 –