use variable in FROM statement

二次信任 提交于 2019-12-12 19:17:55

问题


I am trying to create a query that will be executed once for a specific table in a specific database in each server in sys.server.

For each server.database.dbo.table I want to know the contents.

So what I need is something like:

declare @numrows int = (select count(*) from sys.servers)
declare @i int = 1

while @i <= @numrows
BEGIN
declare @servername varchar(max) = (select servernaam from #servers where rij = @i)

select * from @servername.DATABASE.DBO.TABLE

set @i = @i+1

END

However, the @servername in @servername.DATABASE.DBO.TABLE does not seem to work.

Suggestions? Thanks for thinking with me.


回答1:


You have to use dynamic sql:

declare @numrows int = (select count(*) from sys.servers)
declare @i int = 1
declare @Sql(1000)
declare @servername varchar(max)

while @i <= @numrows
BEGIN
select @servername = servernaam 
from #servers where rij = @i

set @Sql = 'select * from '+@servername+'.DATABASE.DBO.TABLE'
exec(@Sql)

set @i = @i+1

END

Here is more informations about exec.



来源:https://stackoverflow.com/questions/12508973/use-variable-in-from-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!