Avatar of Mike2015
 asked on

Use xp_create_subdir with Non Administrative accounts


I'm trying to allow non admins to use the xp_create_subdir function (Responsibly) in T-SQL 2016 environment within a stored procedure. We have a process in place where we keep billing backup (Proof of work) in an invoice folder.  Once the file is billed we need to create the next iteration of that billing number. Example for file 12345.  Once we bill 12345-1 we want to create a folder called 12345-2.

I've created a user account that will be used as a service account. This was done so rights to the folder location could be granted.  Inside the database I've created the stored procedure using "WITH EXECUTE AS OWNER" as I do not wish to grant all users the ability to use xp_create_Subdir. I’ve created a new schema just for this sp, the schema owner has been set to the service account. I’ve added the service account as the schema owner, db_Owner, and sysadmin.  Only the sysadmin permission is required, but I want to try to alleviate any suggestions I've already tried. I’ve also granted execute rights to the xp_Create_subdir function to the service account.
The execute line is fairly generic:
DECLARE @FilePath varchar(255)
SET @FilePath = ‘[File Path]’
EXEC master.dbo.xp_create_subdir @FilePath

I have run the script myself (sysadmin) and it works.  However as soon as it’s put in a stored procedure it fails with error:
Msg 22048, Level 16, State 1, Line 2
Error executing 'xp_create_subdir': Permission denied. User must be a member of 'sysadmin' server role.

I’ve also tried adding myself (sysadmin) as the owner of the stored procedure, schema, and database, then executed the stored procedure under my sysadmin login, and get the same error.  What am I missing?
DatabasesMicrosoft SQL Server

Avatar of undefined
Last Comment

8/22/2022 - Mon
Scott Pletcher

View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.

That was my missing piece.  Thank you!
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes