2013-08-26 110 views
0

我已經成功地在2008年創建的SQL函數:函數返回空集

ALTER FUNCTION [dbo].Func_raw_data_xref (@ColName AS NVARCHAR(255)) 
RETURNS @VVSrcCDs TABLE ( 
    VV_SRC_CD  NVARCHAR(255) NULL, 
    VV_CD   NVARCHAR(255) NULL, 
    VV_SRC_CD_DESC NVARCHAR(255) NULL, 
    VV_DSC   NVARCHAR(255) NULL) 
AS 
    BEGIN 
     DECLARE @vv_SRC_CD  NVARCHAR(255), 
       @vv_CD   NVARCHAR(255), 
       @vv_SRC_CD_DESC NVARCHAR(255), 
       @vv_DSC   NVARCHAR(255); 

     SELECT @vv_SRC_CD = A.VV_SRC_CD, 
      @vv_CD = A.VV_CD, 
      @vv_SRC_CD_DESC = A.VV_SRC_CD_DESC, 
      @vv_DSC = A.VV_DSC 
     FROM DBO.VALUES A 
      JOIN VVLOOKUP B 
       ON A.VV_SRC_CD = b.VV_SRC_CD 
     WHERE B.[CLIENT COLUMN NAME] = @ColName 

     RETURN; 
    END 

問題是,當我調用該函數:

SELECT * 
FROM DBO.Func_raw_data_xref('_CD'); 

我沒有得到任何結果。我得到的是函數中引用的列,但沒有數據。如果我將select語句複製到函數外並使用@ColName的有效參數運行它,我確實會得到結果。

回答

2

您不必將選擇的結果賦給局部變量。你所要做的就是那個INSERT結果SELECT INTO表變量你聲明爲返回值:

而不是

DECLARE 
    @vv_SRC_CD NVARCHAR(255), 
    @vv_CD NVARCHAR(255), 
    @vv_SRC_CD_DESC NVARCHAR(255), 
    @vv_DSC NVARCHAR(255); 

    SELECT 
     @vv_SRC_CD = A.vv_SRC_CD, 
     @vv_CD = A.vv_CD, 
     @vv_SRC_CD_DESC = A.vv_SRC_CD_DESC, 
     @vv_DSC = A.vv_DSC 
    FROM DBO.values A 
    JOIN VVLookup B 
    ON A.vv_SRC_CD = b.vv_SRC_CD 
    WHERE B.[Client Column Name] = @ColName 

嘗試

INSERT INTO @VVSrcCDs 
SELECT 
      A.vv_SRC_CD, 
      A.vv_CD, 
      A.vv_SRC_CD_DESC, 
      A.vv_DSC 
     FROM DBO.values A 
     JOIN VVLookup B 
     ON A.vv_SRC_CD = b.vv_SRC_CD 
     WHERE B.[Client Column Name] = @ColName