2
DECLARE @id bigint=0,
    @id int=0,
    @name varchar(50) = '36',
    @marks int = 'SDFGS'
    @Op varchar(50) = 'UPSERT'

    IF(@Op='UPSERT')
    BEGIN
        INSERT INTO tbl_student     
        (name, marks)
        VALUES 
        (@name, @marks)
        SELECT SCOPE_IDENTITY()     
    END
    ELSE
    BEGIN
         UPDATE tbl_student SET
         name = @name,
         marks = @marks
         WHERE id = @id
         SELECT 'Success'
    END

It throw error 'Conversion failed when converting the varchar value 'SDFGS' to data type int.'

I want to handle this error.

If error then it will be return 'Error' string.

3 Answers 3

1

You can handle this error using TRY... CATCH Block

Begin
declare @msg varchar(100)
Begin try
DECLARE @id bigint=0,@name varchar(50) = '36',@marks int = 'SDFGS',@Op varchar(50) = 'UPSERT'

IF(@Op='UPSERT')
BEGIN
    INSERT INTO tbl_student     
    (name, marks)
    VALUES 
    (@name, @marks)
    SELECT SCOPE_IDENTITY()     
END
ELSE
BEGIN
     UPDATE tbl_student SET
     name = @name,
     marks = @marks
     WHERE id = @id
     SELECT 'Success'
     Set @msg='Success'
END

End try
Begin catch
SELECT 'Error'
Set @msg='Error'
 End catch

End
Sign up to request clarification or add additional context in comments.

Comments

0

You can use TRY ... CATCH

https://msdn.microsoft.com/en-us/library/ms175976.aspx - there is a sample code here.

Comments

0

The error says it all, you are trying to put a string value in an int datatype and hence the error. If you want to catch this error then try to use TRY...CATCH. Something like

BEGIN TRY  
    -- Your code.   
END TRY  
BEGIN CATCH  
    -- Catch the exception/error here.   
END CATCH; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.