从EXEC语句SQL Server创建表或视图

时间:2017-02-07 22:31:13

标签: tsql view sql-server-2008-r2 linked-server

var result = OnDemandHistory.Where(c => machineID.Contains(c.MachineID))
                            .OrderByDescending(c => c.ODHisDate);

我需要将EXECUTION语句生成的结果转储到视图中。这可能吗?我猜测这种方式编写查询是出于性能原因

1 个答案:

答案 0 :(得分:1)

您可以使用openquery在远程服务器上运行SELECT,并从结果集中创建一个视图。

这是一个代码示例。该示例创建local1作为链接服务器并对其执行查询。如果已经注册了链接服务器,则无需运行步骤1和步骤4。

-- Step 1. register a linked server
exec sp_addlinkedserver 
        @server = 'local1',
        @srvproduct = '',
        @provider='SQLNCLI',
        @datasrc = 'NameOfTheRemoteServer' -- if server has multiple instances use 'NameOfTheServer\NameOfTheInstance'
go

-- Step 2. run the query on remote server and create a view out of the results
create view ViewTest
as
select * from openquery(
    local1, 
    'select 
        top 10 
        lower(AddressLine1) as Street,
        ModifiedDate as dt
    from AdventureWorks2014.Person.Address'
    )
go

-- Step 3. check the view
select * from ViewTest
go

-- Step 4. finally drop the linked server
sp_dropserver 'local1'
go