2012-10-23 82 views
1

我已經創建了微軟SSMS標量值功能,如下:標量值函數不返回預期的結果

CREATE FUNCTION [dbo].[fGetCurrentBalFromName] 
(
    @Name NVarchar, 
    @CliFl Bit 
) 
RETURNS Money 
AS 
BEGIN 
    DECLARE @CurrentBal Money 

    select @CurrentBal=SUM(tt.Debt) from 
    (select case t.Clientfl when 1 then dbo.fGetClientNameFromId(t.AgentID) 
        else dbo.fGetSupplierNameFromId(t.AgentID) 
      end as Cli, 
      t.Clientfl, 
     case t.Clientfl when 1 then 
      case t.Incomfl 
       when 1 then t.Amount 
         else (-1)*t.Amount 
      end 
     else 
      case t.Incomfl 
       when 1 then (-1)*t.Amount 
         else t.Amount 
      end 
     end as Debt    
     from [Store].[dbo].[Money] t) tt where [email protected] and [email protected] 
     group by tt.Cli 

    RETURN @CurrentBal 

END 

當我執行

Select dbo.fGetCurrentBalFromName('Вали',1) 

我沒有得到任何(NULL)結果。

但是,當我嘗試不帶參數

select SUM(tt.Debt) from 
     (select case t.Clientfl when 1 then dbo.fGetClientNameFromId(t.AgentID) 
         else dbo.fGetSupplierNameFromId(t.AgentID) 
       end as Cli, 
       t.Clientfl, 
      case t.Clientfl when 1 then 
       case t.Incomfl 
        when 1 then t.Amount 
          else (-1)*t.Amount 
       end 
      else 
       case t.Incomfl 
        when 1 then (-1)*t.Amount 
          else t.Amount 
       end 
      end as Debt    
      from [Store].[dbo].[Money] t) tt where tt.Cli='Вали' and tt.Clientfl=1 
      group by tt.Cli 

我得到我想要的東西單獨執行查詢。 那麼,我爲創建標量值函數所犯的錯誤是什麼。 任何幫助將不勝感激!

回答

4

您需要指定參數@Name的大小。

@Name NVarchar 

沒有大小,它默認爲1個字符。

嘗試類似這樣的東西。

@Name NVarchar(100) 

SQL Fiddle

+0

太謝謝你了!我不認爲我能犯這樣一個愚蠢的錯誤。 –