在OPENQUERY语句中使用'use'

时间:2013-08-01 06:03:45

标签: sql sql-server tsql

是否可以在OPENQUERY中执行'use'语句?

这有效:

SELECT *
FROM OPENQUERY(
    server_name, 
    'select * from AdventureWorks.Person.Address'
)

这不是:

SELECT *
FROM OPENQUERY(
    server_name, 
    'use AdventureWorks; select * from Person.Address'
)

1 个答案:

答案 0 :(得分:0)

试试这个 -

DECLARE 
      @SQL NVARCHAR(500)
    , @ServerName NVARCHAR(100) = 'server_name'
    , @DbName NVARCHAR(100) = DB_NAME() -- current db_name

SELECT @SQL = '
SELECT *
FROM OPENQUERY(
    '+ @ServerName + ', 
    ''SELECT * FROM [' + @DbName + '].Person.Address''
)'

PRINT @SQL
EXEC sys.sp_executesql @SQL