SQL Server如何在远程服务器上的特定数据库中创建视图

时间:2017-01-20 19:25:00

标签: sql-server tsql sql-server-2012

我正在编写一个动态SQL语句来在特定数据库中的远程服务器上创建视图。我生成的SQL语句在master数据库上执行。如果我使用CREATE VIEW语句中的3部分命名约定没有帮助。

--QUERY
SELECT 
    'IF OBJECT_ID(N'''+ ss.name +'.view_' + so.name + ''') IS NULL
        EXECUTE (''CREATE VIEW ' + ss.name + '.view_' + so.name + ' AS SELECT * FROM REMOTEDATABASE.' + ss.name + '.' + so.name + ''') AT [REMOTESERVER]' 
   FROM sys.objects so
   JOIN sys.schemas ss
     ON so.[schema_id] = ss.[schema_id] 
  WHERE so.[type] = 'U';

--Query Result
IF OBJECT_ID(N'dbo.view_Test') IS NULL 
    EXECUTE ('CREATE VIEW dbo.view_Test AS SELECT * FROM REMOTEDATABASE.dbo.Test') AT [REMOTESERVER]

2 个答案:

答案 0 :(得分:0)

要在远程服务器的特定数据库中创建视图,请尝试以下操作:

EXECUTE ('USE YourDatabase EXEC(''CREATE VIEW YourView AS SELECT 1 AS SomeColumn'')') AT YourRemoteServer

答案 1 :(得分:-1)

以下对我有用:

USE YourDatabaseName  

GO  

CREATE VIEW [ViewName]  
AS  
SELECT 1