sys.database_principals is not executed in current database if called from sp procedure (stored in master)

StackOverflow https://stackoverflow.com/questions/14981514

  •  10-03-2022
  •  | 
  •  

Question

I would like to print out database users of an actual database in a SP procedure (see the code of sp_PrintUsers below), however, for some reason it print out database users of master. It seems that it is a general behavior of SP procedure for all database-level views despite the fact that any database-level SQL statement is executed in the actual database. If we print out the DB_NAME that it is clearly not master, so what is wrong?

Is there any workaround?

use [master]
go
create procedure sp_PrintUsers
as
begin
    SELECT DB_NAME() AS DataBaseName
    select name from sys.database_principals;
end
go

use [actual_database]
go

exec sp_PrintUsers
Was it helpful?

Solution

Try executing the select dynamically as in:

EXEC('select name from sys.database_principals;');

If that does not help build the query to reference the catalog view with a three part name.

OTHER TIPS

Try this :

use [master]
go
create procedure sp_PrintUsers
as
begin
    declare @dbname varchar(30) = DB_NAME()
    EXEC ('select name from ' + @dbname + '.sys.database_principals');        
end
go

use [actual_database]
go

exec sp_PrintUsers
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top