SQL Server:查询循环

时间:2013-10-29 20:58:23

标签: sql sql-server

我需要获取所有应用程序数据库,并且我已经能够通过

获得该数据库
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

2 个答案:

答案 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

要记住以下几点:

  • 您的动态SQL变量需要足够长以容纳SQL内容和数据库名称。
  • 我将sys.database更改为sys.databases,因为这是表的名称
  • 如果您需要聚合用户名,ID和Read Accesses列表,我建议您创建另一个临时表。这可能是一个好主意,因为如果你有很多数据库,你的结果集可能会有点难以管理。

答案 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