2

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

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

9 Comments

You cannot use SP_EXECUTESQL in this way, you still have to use string concatenation to make the query in the same way as you did for EXEC(), although I'd still advocate using SP_EXECUTESQL. I would also advise using 'SELECT * FROM ' + QUOTENAME(@Servername) + '.DATABASE.SCHEMA.TABLE' to allow for any server names with reserved characters in, or Server names that are reserved words.
@GarethD t-clausen.dk You have right! Thanks! I edited the. post
@t-clausen.dk - what's wrong with declare inside a loop? declares don't participate in control flow at all.
@Damien_The_Unbeliever Maybe it's work correctly It's not good practice.
@Parado: could you elaborate on that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.