简体   繁体   中英

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.

I'm using TRY CATCH blocks to catch If error occured. I'm selecting ERROR_LINE() and ERROR_MESSAGE() in CATCH block.

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...

In column are 100000+ values and I don't know on which value error occured. So I need to check over 100000 values?

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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