我需要获取所有应用程序数据库,并且我已经能够通过
获得该数据库select name from sys.database where database_id > 6
现在,我需要运行以下查询:
select
User_FirstName
, User_Name
, User_Id
, User_ReadAccess
from
[name obtained from sys.databases].dbo.ADMN_User_Details
这是我到目前为止所写的内容,我在database_Name.dbo.ADMN.User_Details
收到错误:
declare @database_name varchar(50)
declare @User_FirstName varchar (50)
declare @User_Name varchar (50)
declare @User_Access int
declare @User_Id varchar (50)
declare Maximizer cursor FOR
select name from sys.databases
where database_id > 6
open Maximizer
fetch next from Maximizer into @database_name
while (@@FETCH_STATUS=0)
begin
select
@User_FirstName, @User_Name, @User_Id, @User_Access
from
@database_Name.dbo.ADMN.User_Details
end
close Maximizer
deallocate Maximizer
有人可以帮我吗?
谢谢,
DB
答案 0 :(得分:9)
只要您在系统管理上下文中使用动态SQL而不是在野外,就可以使用动态SQL。
--@sql holds your dynamic sql, @db holds the current DB
declare @sql varchar(1000)
declare @db varchar(100)
--populate your list of databases through which you'll iterate.
select name, 0 as run
into #dbs
from sys.databases where database_id > 6
--a while loop in sql...don't tell Jeff Moden
while exists (select 1 from #dbs where run = 0)
begin
set @db = (select top 1 name from #dbs where run = 0 order by name)
set @sql = '
select ''' + @db + '''
, User_FirstName
, User_Name
, User_Id
, User_ReadAccess
from '+ @db +'.dbo.ADMN_User_Details'
exec(@sql)
update #dbs
set run = 1
where name = @db
end
要记住以下几点:
答案 1 :(得分:0)
您需要使用动态sql在查询中连接变量名,例如:
DECLARE @sql
declare @database_name varchar(50)
declare @User_FirstName varchar (50)
declare @User_Name varchar (50)
declare @User_Access int
declare @User_Id varchar (50)
declare @sql VARCHAR(MAX)
declare Maximizer cursor FOR
select name from sys.databases
where database_id > 6
open Maximizer
fetch next from Maximizer into @database_name
while (@@FETCH_STATUS=0)
begin
PRINT @database_Name
SET @sql = '
select '+@User_FirstName+', '+@User_Name+', '+@User_Id+', '+@User_Access+' from '+@database_Name+'.dbo.ADMN.User_Details
'
EXEC (@sql)
end
close Maximizer
deallocate Maximizer