简体   繁体   English

如何检测哪个值发生错误?

[英]How to detect on which value error occured?

Imagine that I have stored procedure which It trying to check If value is of type datetime and convert It to date. 想象一下,我有一个存储过程,它试图检查其值是否为datetime类型,并将其转换为日期。

I'm using TRY CATCH blocks to catch If error occured. 我正在使用TRY CATCH块来捕获是否发生错误。 I'm selecting ERROR_LINE() and ERROR_MESSAGE() in CATCH block. 我在CATCH块中选择ERROR_LINE()ERROR_MESSAGE()

Problem is that ERROR_LINE() returning only row number of procedure where error occured (and sometimes It returning wrong row) and ERROR_MESSAGE() returning only error's description like Conversion failed when converting... 问题是ERROR_LINE()仅返回发生错误的过程的行号(有时返回错误的行),而ERROR_MESSAGE()仅返回错误的描述,如Conversion failed when converting...

In column are 100000+ values and I don't know on which value error occured. 列中有100000多个值,我不知道发生在哪个值上的错误。 So I need to check over 100000 values? 所以我需要检查超过100000个值?

Here is anyway to print Error message + Value on which error occured? 无论如何,这里都可以打印错误消息+发生错误的值?

You can try like this: 您可以这样尝试:

if(isDate(yourdatevalue))
begin
  --some code
end
else
begin
print yourdate + 'There is an error'
end

you can use RAISERROR as : 您可以将RAISERROR用作:

DECLARE @Test TABLE (id INT, varchardate VARCHAR(200))

INSERT INTO @Test VALUES (1,'200410212'),(2,'A'),(3,'2015-04-24 08:08:01.083')  


DECLARE @err_message nvarchar(255)


DECLARE @varchardate VARCHAR(200), @Id int
DECLARE @getvarchardate CURSOR
SET @getvarchardate = CURSOR FOR
    SELECT varchardate ,id
    FROM @Test
    OPEN @getvarchardate
    FETCH NEXT
    FROM @getvarchardate INTO @varchardate ,@Id
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF isDate(@varchardate) = 0
        begin
        SET @err_message = @varchardate + ' and ' 
        + CAST (@Id AS VARCHAR(10)) + ' Not valid Date'
        RAISERROR (@err_message, 11,1)
        END
        ELSE
        begin
        SELECT id,varchardate
        FROM @Test  
        END

FETCH NEXT
FROM @getvarchardate INTO @varchardate ,@Id
END
CLOSE @getvarchardate
DEALLOCATE @getvarchardate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM