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)); 
4

1 回答 1

2

如果你这样调用你的程序

Exec sp_getClientTransactioninfo '2001-01-01'

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

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

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

因此,如果您不提供参数,它将默认为 null,然后您的错误消息会显示。

您可能还想研究RAISEERROR而不是PRINT

于 2013-07-24T00:50:13.927 回答