2013-07-23 51 views
0

我在這裏有一個存儲過程執行正常,但我的自定義錯誤消息不工作時,我省略了一個參數。相反,我得到了默認的錯誤信息。存儲過程錯誤處理當參數被忽略

有誰知道我在做什麼錯?我使用SQL Server 2012的

因此,舉例來說,當我把它叫做

Exec sp_getClientTransactioninfo '2001-01-01' 

應打印

'This is the error msg= To Date required. Please enter To Date' 

但事實並非如此。

Alter PROCEDURE sp_getClientTransactioninfo 
@FromDate DATETIME, 
@ToDate DATETIME, 
@Active int 

AS 
Set NOCOUNT ON 
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

-- Variables to handle error msg 
Declare @error int, @errorMessage varchar(200) 
SET @error = 0; 
SET @errorMessage = ''; 

IF (@FromDate IS NULL) 
BEGIN 
SET @error = -1 
SET @errorMessage = 'From Date required. Please enter From date' 
GOTO Final_Process 
END 

IF (@ToDate IS NULL) 
BEGIN 
SET @error = -1 
SET @errorMessage = 'To Date required. Please enter To Date' 
GOTO Final_Process 
END 

IF (@Active IS NULL) 
BEGIN 
SET @error = -1 
SET @errorMessage = 'Active status required. Please enter active status' 
GOTO Final_Process 
END 

Select RestaurantID, ClientName as Client, Mem_Name as Member, Mem_Address as Address,    Sum(AmountSpent) as 'Amount Spent', 
--((membersamt)/totclientamt)*100 
convert(varchar,floor(round((SUM(mv.AmountSpent)/ (select SUM(AmountSpent) from   UDC_MemberVisits umv where 
umv.RestaurantId=mv.RestaurantId)) 
* 100,0)))+'%' as perAmountSpent 

from dbo.UDClub_Client as C 
join dbo.UDC_MemberVisits as MV on MV.RestaurantId = C.ClientID 
join dbo.UDC_Member as M on M.Mem_ID = MV.MemberID 

where MV.DateVisited between @FromDate and @ToDate 

group by ClientName, Mem_Name, Mem_ID, RestaurantID, Mem_Address 
order by ClientName 

--Error Handling 

Declare @ErrorVar INT 
SET @ErrorVar = @@ERROR 
IF @@Error <> 0 
Final_Process: 
Print 'This is the error msg=' + @errorMessage 
Print 'Error code =' + CAST(@error as NVARCHAR(8)); 
+0

什麼是你的DBMS? –

+0

SQL Server 2012 – CSharper

回答

1

如果你這樣調用

Exec sp_getClientTransactioninfo '2001-01-01' 

你的程序然後你會得到一個錯誤,指出該過程需要缺少的參數@ToDate。缺少的參數沒有設置爲null,它只是不存在,所以SQL Server在執行過程之前會拋出一個錯誤,表示它期待參數。

可以解決這個問題,在你的程序中聲明你的參數設置爲NULL,就像這樣:

Alter PROCEDURE sp_getClientTransactioninfo 
@FromDate DATETIME = null, 
@ToDate DATETIME = null, 
@Active int 

所以,如果你不提供參數,則默認爲空,那麼你的顯示錯誤信息。

您可能還需要尋找到RAISEERROR而不是PRINT

+0

謝謝,這工作。我也必須設置@Active int = null – CSharper