我试图将服务器名称作为Exec(@sqlstring)
存储过程中的变量传递。但是我无法获得正确的语法,而且几乎所有的想法都是如此。
服务器名称是UK-DATA-SQL-P01或UK-DATA-SQL-P02,这就是我需要将其用作变量以便用户可以选择的原因。
我试图用来传递变量的语法是:
INNER JOIN ' + @ServerName + '.' + @DBName + '.[dbo].
我确信这很简单,但我们非常感谢任何帮助。
提前致谢
答案 0 :(得分:0)
使用这样的东西只是一个样本然后你可以扩展
create proc sampleProc
@tableName varchar(100) ,
@serverName varchar(100)
as
begin
declare @tableName1 varchar(100)
set @tableName1='Sales'
declare @fullname varchar(500)
set @fullname = @serverName+'.'+ @tableName
print (@fullname)
DECLARE @SQLQuery AS NVARCHAR(500)
SET @SQLQuery = ' SELECT * FROM '+ @fullname + ' inner join ' + @tableName1 + ' on id=custid'
print (@SQLQuery)
--EXECUTE(@SQLQuery)
end
--usage like this
exec sampleProc 'server','customer'
declare @tableName varchar(100)
set @tableName='Customers'
-- this is previous answer
declare @tableName1 varchar(100)
set @tableName1='Sales'
DECLARE @SQLQuery AS NVARCHAR(500)
SET @SQLQuery = ' SELECT * FROM '+ @tableName + ' inner join ' + @tableName1 + ' on id=custid'
print (@SQLQuery)
EXECUTE(@SQLQuery)
答案 1 :(得分:0)
您也可以使用 OPENDATASOURCE 。像这样:
INNER JOIN OPENDATASOURCE('SQLOLEDB','Data Source = ServerName; User ID = Username; Password = Password').[DatabaseName].[DatabaseOwner].[TableName] Z ON...
PS。您需要启用Ad Hoc Distributed Queries才能使其正常工作。
How To Enable Ad Hoc Distributed Queries - 供参考
希望它有所帮助。
答案 2 :(得分:0)
我一直在使用同义词来实现类似的目标:
Create Procedure ReturnServerDbTable (@Server as nvarchar(50), @DB as nvarchar(50), @Table as nvarchar(50))
as
begin
declare @sql as nvarchar(500)
set @sql = 'CREATE SYNONYM ServerDBTable FOR ' + @Server + '.' + @db + '.dbo.' + @table
exec(@sql)
select * from ServerDBTable
DROP SYNONYM ServerDBTable
end