Dynamically creating Schema, new user and "Run As" new user

  • Hi.

    I am trying to create a new schema in my database (currently only dbo exists). And this is being done via series of stored Procedures that I call from .NET.

    My issue is that after creating this new schema, and the new user - i am not able to test SP by impersonating it. Here are the steps:

    1. Create new schema user
      exec ('CREATE USER ' + @s_NewSchemaUser + ' WITHOUT LOGIN WITH DEFAULT_SCHEMA = ' + @s_NewSCHEMA)
      print 'User created'
      exec ('GRANT VIEW DEFINITION ON SCHEMA::' + @s_SRCSCHEMA + ' TO ' + @s_NewSchemaUser)
      exec ('GRANT CREATE PROCEDURE TO ' + @s_NewSchemaUser)
      exec ('GRANT CREATE TABLE TO ' + @s_NewSchemaUser)
      exec ('GRANT CREATE VIEW TO ' + @s_NewSchemaUser)
      exec ('GRANT CREATE FUNCTION TO ' + @s_NewSchemaUser)?

    2. Create new schema
      Create new schema
      exec ('CREATE SCHEMA ' + @NewSchemaName + ' AUTHORIZATION ' + @NewSchemaUser)?

    3. Then i programmatically copy definitions of tables, SP, functions etc into this new schema.

    Problem is that I cannot test it. In SSMS I run the following command:

    EXECUTE AS LOGIN = @NewSchemaUser;
    exec @NewSchemaName.[uspGetReportMyCustomReport]
    REVERT;

    I get the error:

    Cannot execute as the server principal because the principal "new schema user name" does not exist, this type of principal cannot be impersonated, or you do not have permission.

     

    I read on google about the difference between users and logins, and I realize that I cannot impersonate as this user because it does not have an associated login. At least not the way I created it. But I am also not able to map existing login to this user since SSMS complains that there is already a user associated with login.

    Any idea what the right way for creating this user will be? so i can impersonate it (it will have lesser privileges then dbo).

    How To Post[/url]

  • If you want to be able to impersonate it, you're going to need to create Logins (and now you have a new problem). If you just want different schemas to be accessible by the same user, you don't need new users or impersonation, you just need to set appropriate permissions on the schema.

  • Did you try 'EXECUTE AS USER ='?  Would that help you here?

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Ah - I switched to execute as user, and i see better results now.

    Thanks a ton for pointing that out !

    How To Post[/url]

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply