SQL 如何在 RAISERROR 方法中打印 DateTime 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6181734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:47:59  来源:igfitidea点击:

How to print DateTime variable in the RAISERROR method?

sqlsql-serversql-server-2005stored-proceduresraiserror

提问by vinayvasyani

My Stored Procedure accepts two params @EffectiveStartDate DATETIME
@EffectiveEndDate DATETIME

我的存储过程接受两个参数 @EffectiveStartDate DATETIME
@EffectiveEndDate DATETIME

I wrote the validation code as this:

我写的验证代码是这样的:

IF(@EffectiveStartDate > @EffectiveEndDate)
        BEGIN
            RAISERROR ('SPName: InsertUpdateLiquidityDateRule:  Start Date: %s cannot  be greater than End Date %s',11,1,CAST(@EffectiveStartDate AS varchar(30)),CAST(@EffectiveEndDate AS varchar(30)));
            RETURN -1
        END 

May I know what am I doing wrong here.

我可以知道我在这里做错了什么。

While Compiling my SProc, it raised the message 'Incorrect syntax near CAST()'

在编译我的 SProc 时,它提出了消息“CAST() 附近的语法不正确”

回答by Alex Aza

The supplied value must be a constant or a variable. You cannot specify a function name as a parameter value. (from MSDN Executing Stored Procedures).

提供的值必须是常量或变量。您不能将函数名称指定为参数值。(来自 MSDN执行存储过程)。

You need to do something like this:

你需要做这样的事情:

declare @EffectiveStartDateText varchar(30)
set @EffectiveStartDateText = cast(@EffectiveStartDate as varchar)

declare @EffectiveEndDateText varchar(30)
set @EffectiveEndDateText = cast(@EffectiveEndDate as varchar)

RAISERROR (
    'SPName: InsertUpdateLiquidityDateRule:  Start Date: %s cannot  be greater than End Date %s',
    11,
    1,
    @EffectiveStartDateText,
    @EffectiveEndDateText);

回答by Chris Singleton

Just trying to help out, here is another example. I put this in the BEGIN CATCH statement after my BEGIN TRY.

只是想帮忙,这是另一个例子。我在 BEGIN TRY 之后把它放在 BEGIN CATCH 语句中。

Note: This is very similar to using an if statement.

注意:这与使用 if 语句非常相似。

BEGIN TRY
--Do something.
END TRY 

BEGIN CATCH
    --Else on error do this.
    PRINT 'Problem found!!! ' 

    -- Whoops, there was an error
    -- Raise an error with the details of the exception
    DECLARE @ErrMsg nvarchar(4000), 
            @ErrSeverity int, 
            @ErrLineNum int

    SELECT @ErrMsg = ERROR_MESSAGE(), 
           @ErrSeverity = ERROR_SEVERITY(), 
           @ErrLineNum = ERROR_LINE()

    RAISERROR(@ErrMsg, @ErrSeverity, 1, @ErrLineNum)

END CATCH