从View - SQL Server调用远程函数

时间:2012-05-13 09:02:09

标签: sql-server remote-server

我正在寻找一种方法来调用REMOTE FUNCTIONSELECT子句中的VIEW。 基本上我试图做这样的事情:

    CREATE VIEW [dbo].[View_Year_Forcast] AS
        (SELECT    BshForecast.ProjectId, 
                   BshForecast.JobTypeId,
                   Job_Type.NAME,          
                   ProjectName , 
                   ProjectManagerID,                       
                   ProjectManagerName , 


***EXEC @START_DATE  =[192.168.0.10].[LudanProjectManager].[dbo].[func_Project_Get_Start_Date] @PROJECT_ID as [Start_Date],***

                   StartBudget , 
                   AdditionalBudget , 
                   TotalBudget  , 
                   UsedBudget ,   
        FROM       BshForecast  INNER  JOIN Job_Type ON BshForecast.JobTypeId = ID                   
        WHERE   (dbo.BshForecast.Year = DATEPART(YYYY,GETDATE()))   
                AND (dbo.BshForecast.IsDeleted = 0) 
                AND (dbo.BshForecast.BranchId = 200)
                AND (dbo.BshForecast.Approved = 1) );

我想要得到的是第七列将保留每个项目的开始日期,该日期将从远程服务器中的函数进行评估。

1 个答案:

答案 0 :(得分:2)

我知道调用远程函数的唯一方法是openquery。但openquery只接受字符串文字,因此您必须将调用包装在openquery中的exec

这是一个创建函数并通过名为“localhost”的链接服务器调用它的示例。

use TestDatabase
if exists (select * from sys.objects where name = 'fn_twice')
    drop function fn_twice
go
create function dbo.fn_twice(@i int) returns int as begin return 2*@i end
go
declare @i int
set @i = 21

declare @func_sql nvarchar(max)
set @func_sql = 'select @result = a.result from openquery(localhost, ' +
        '''select TestDatabase.dbo.fn_twice(' + 
        cast(@i as varchar(12)) + ') as result'') a'

declare @result int
exec sp_executesql @func_sql, N'@result int output', @result output

-- The result of the function call is now available in @result, and
-- you can use it in a query.