• zoggling - Tuesday, February 6, 2018 3:31 AM

    We have a number of T-SQL statements contained in a variable @SQL nvarchar(MAX) which need to be executed within a stored procedure at runtime. For example:

    CREATE mysproc AS
    DECLARE @SQL nvarchar(MAX);
    SELECT @SQL = 'DELETE FROM db1.dbo.Table1;'
    SELECT @SQL += 'DELETE FROM db2.dbo.Table1'
    SELECT @SQL += 'DELETE FROM db3.dbo.Table1'
    EXEC (@SQL);
    GO

    However, we are receiving errors relating to security around this.

    We suspect we may need to create a SQL login, which is mapped to all relevant databases within the instance, and then create individual users within each database which map to this login, before applying the db_datareader database role to each user.

    We have done this, however  this is returnning the following error  message:

    The server principal "S-1-9-3-1979612751-1205369817-371524777-3428266560." is not able to access the database "db1" under the current security context.

    Is anyone please able to  detail what we need to do to achieve this? We don't want to open up any vulnerabilities, but require the stored procedure to be able to delete data from tables across several databases  as detailed above.

    Many thanks

    If you want to delete, you'll need more than db_datareader.  But I don't think that's the cause of your error message.  I take it the login you created isn't called S-1-9-3-1979612751-1205369817-371524777-3428266560?  Do you get the same error in every database?  What do you get if you run this query (it's from memory so the columns and syntax may not be 100% correct)?

    SELECT * FROM sys.server_principals l
    JOIN db1.sys.database_principals u ON l.sid = u.sid
    WHERE l.name = 'MyLoginName'

    John