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'
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.