I have a few machine running databases and the database tables names have the machine name included in them.
Say machine1, machine2, machineN
are the machine names. The database names tables are like <machineName>_cm.dbo.TableName
and an example would be machine1_cm.dbo.cmobjects
.
How can I insert a variable that would pickup the machine name and append the _cm.dbo.Tableme
to it as part of a SQL query that I need to run on all these machines?
SELECT columnName1, columnName2, columnName3
FROM machine1_cm.dbo.DMOBJNAMES ...
I was thinking something like the following would work but it's not:
SELECT columnName1, columnName2, columnName3
FROM @@servername+_cm.dbo.MYOBJNAMES;
or
SELECT columnName1, columnName2, columnName3
FROM SERVERPROPERTY('MachineName' _cm..dbo.MYOBJNAMES;
1条答案
按热度按时间von4xj4u1#
You can use dynamic SQL.
Don't forget to parameterize where possible, you can pass parameters to
sp_executesql
Alternatively you can execute the whole batch in the context of that database