如何以Sysadmin身份运行存储过程?

时间:2011-08-26 18:26:30

标签: sql-server-2005 stored-procedures xp-cmdshell

我不想授予用户Sysadmin角色。 有没有办法以Sysadmin或sysadmin用户身份运行特定存储过程? 存储过程在MSSQL 2005中,并具有xp_cmdshell 以下是代码:

ALTER PROCEDURE [dbo].[procExcelQuotebyItem] 
(
    @OrderNumber INT
)
AS

BEGIN
SET NOCOUNT ON


DECLARE @Cmd varchar(1000)
DECLARE @fn varchar(500)
DECLARE @provider varchar(100)
DECLARE @ExcelString varchar(100)

--  New File Name to be created
SET @fn = 'D:\Pre-Manufacturing\Excel\QuotebyItem.xls'

/*Cleanup*/

SET @Cmd = 'DEL ' + @fn
EXEC xp_cmdshell @Cmd, no_output

--  FileCopy command string formation
SET @Cmd = 'Copy D:\Pre-Manufacturing\Excel\QuotebyItemTemplate.xls ' + @fn

--  FileCopy command execution through Shell Command
EXEC MASTER..XP_CMDSHELL @cmd, NO_OUTPUT

--  Mentioning the excel destination filename
SET @provider = 'Microsoft.Jet.OLEDB.4.0'
SET @ExcelString = 'Excel 8.0;Database=' + @fn

EXEC('INSERT INTO OPENROWSET(''' + @provider + ''',''' + @ExcelString + ''',''SELECT * FROM [Sheet1$A2:L2]'') 
SELECT [ITEMNUMBER],'''',[ITEM_DESCRIPTION],[CASEPACK],[UNIT PRICE],[CASE PRICE],[WEIGHT],[CUBE],[CASE DIMS],[UPC],[CASE UPC],[Q Comments] FROM [ORDER SUMMERY] WHERE [Order #] = ''' + @OrderNumber + '''')

2 个答案:

答案 0 :(得分:4)

ALTER PROCEDURE dbo.usp_Demo
WITH EXECUTE AS 'USER_ID_with_sysadmin_rights'
AS

http://msdn.microsoft.com/en-us/library/ms188354(v=SQL.90).aspx

测试代码

CREATE PROCEDURE dbo.test1
WITH EXECUTE AS 'CORP\jbooth'
AS
select user_name()
GO
EXEC test1
GO
ALTER PROCEDURE dbo.test1
WITH EXECUTE AS 'dbo'
AS
select user_name()
GO
EXEC test1

使XP_CMDSHELL在SQL 2005中运行的其他信息

SQL 2005 XP_CMDSHELL

答案 1 :(得分:0)

我删除了EXECUTE AS并添加了EXEC sp_addsrvrolemember 'Corporate\HelenS', 'sysadmin'; Works!然后我删除角色EXEC sp_dropsrvrolemember 'Corporate\HelenS', 'sysadmin'