在函数中调用Open Rowset

时间:2014-10-27 09:29:39

标签: sql openrowset

我正在尝试在我的一个用户定义函数中使用openrowset函数。如果我将硬编码查询作为参数传递给函数,它的工作正常。但是如果我将参数传递给查询,它就无法工作。以下是我的功能。请指导 -

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[fnGetOutstandingByCurrencyAsString]
(
    @CustomerID INT
)
RETURNS VARCHAR(MAX)
AS
BEGIN

    DECLARE @Receipts VARCHAR(8000)
    SET @Receipts=''

    DECLARE @Result INT--, @Command VARCHAR(MAX)

    --SET @Command='Exec spUpdateCustomerBilling 1,1'

---这不起作用

 SET @Result=(SELECT 1 from OPENROWSET('SQLNCLI11', 'Server=SERVERNAME;UID=username;Pwd=password;','Exec spUpdateCustomerBilling ' + @CustomerID +',1'))

---这是工作

 SET @Result=(SELECT 1 from OPENROWSET('SQLNCLI11', 'Server=SERVERNAME;UID=username;--Pwd=password;','Exec spUpdateCustomerBilling 1,1'))

SELECT @Receipts=COALESCE(CASE WHEN @Receipts<>'' 
        THEN @Receipts+', '+CurrencyMaster.Code+' '+CONVERT(VARCHAR,Outstanding.Amount) 
        ELSE CurrencyMaster.Code+' '+CONVERT(VARCHAR,Outstanding.Amount) END,'') 
FROM (SELECT * FROM dbo.fnGetOutstandingByCurrencyAsTable (@CustomerID)) Outstanding
INNER JOIN CurrencyMaster ON CurrencyMaster.CurrencyID=Outstanding.CurrencyID

RETURN @Receipts

END

1 个答案:

答案 0 :(得分:0)

将下面的查询框起来作为&#39; dynamic sql&#39; 执行相同的操作,然后在变量@Result

中捕获结果值

DECLARE @CustomerID INT = 50
DECLARE @Result INT

SET @sql = 'SELECT @Result= 1 from OPENROWSET(''SQLNCLI11'',''Server=SERVERNAME;UID=username;Pwd=password;'',''Exec spUpdateCustomerBilling '
           + Cast(@CustomerID AS VARCHAR(10)) + ',1'')'

PRINT @sql

EXEC Sp_executesql
  @sql,
  N'@Result int output',
  @Result output