参数遗漏时的存储过程错误处理

时间:2013-07-23 23:54:58

标签: sql stored-procedures

我这里有一个执行正常的存储过程,但是当我省略参数时,我的自定义错误消息不起作用。相反,我收到默认的错误消息。

有谁知道我做错了什么?我正在使用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)); 

1 个答案:

答案 0 :(得分:1)

如果你这样打电话给你的程序

Exec sp_getClientTransactioninfo '2001-01-01'

然后,您将收到一条错误消息,指出该过程需要缺少参数@ToDate。缺少的参数没有设置为null,它只是不存在,所以SQL服务器抛出一个错误,说它在执行你的程序之前就是期待参数。

您可以通过在过程声明中将参数设置为null来解决此问题,如下所示:

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

因此,如果您不提供参数,则默认为null,然后显示带有show的错误消息。

您可能还想查看RAISEERROR而不是PRINT