title: SQL Server: EXECUTE AS clause of stored procedure not granting sysadmin permissions
body: <p>I developped a stored procedure in order to restore a database from a backup file and add an application user to it. This stored procedure belongs to the master database.</p>
  
  <p>The issue is that my IT department does not allow me to use an admin user, only to use an EXECUTE AS statement with a sysadmin user.</p>
  
  <p>I can restore the database but I can't find a way to add the user at the end of the process.</p>
  
  <p>The code I use:</p>
  
  <pre><code>CREATE PROCEDURE [dbo].[myProc] 
  @database VARCHAR(50)
  WITH EXECUTE AS 'aSysAdminUser' 
  AS
  BEGIN
      --Restore the database (working)
      --Add the application user    (not working)                  
      SET @sqlScript = 'USE '+@database +';
      CREATE USER [myApplicationUser] FROM LOGIN [myApplicationUser];
      EXEC sp_addrolemember ''db_owner'', ''myApplicationUser'''
      EXEC(@sqlScript)
  END
  </code></pre>
  
  <p>When I run it, I have the following error message:</p>
  
  <blockquote>
    <p>The server principal "aSysAdminUser" is not able to
    access the database "database" under the current security context.</p>
  </blockquote>
  
  <p>Any idea how I could create a user in a dynamic parameter db name from a stored procedure on master db using a EXECUTE AS statement?</p>
  
  <p>Thanks</p>