This update will fail as ID is Identity
But I am getting direct error message.
I am getting none of the PRINT statements.
How do I use @@ERROR?
Using SSMS.
Would you call this a script or a query?
PRINT 'start';
DECLARE @ErrorVal INT;
UPDATE IndenText SET ID = 7;
SELECT @ErrorVal = @@ERROR;
PRINT @ErrorVal;
IF @ErrorVal <> 0
BEGIN
PRINT N'A error caught.';
END
PRINT 'done';
This also does not work from me
PRINT 'start';
DECLARE @ErrorVal INT;
BEGIN TRY
UPDATE IndenText SET ID = 7;
SELECT @ErrorVal = @@ERROR;
PRINT @ErrorVal;
END TRY
BEGIN CATCH
IF @@ERROR <> 0
BEGIN
PRINT N'A error caught.' + @@ERROR;
END
END CATCH
PRINT 'done';
I get
Msg 8102, Level 16, State 1, Line 4
Cannot update identity column ‘ID’.
As Martin stated it was a compile error.
Created a constraint that would not be a compile error.
And got the @@ERROR to process.
PRINT 'start';
DECLARE @ErrorVal INT;
DECLARE @newVal INT;
select @newVal = -1;
BEGIN TRY
update Twaste1 set ID = @newVal ;
PRINT 'End Try';
END TRY
BEGIN CATCH
Select @ErrorVal = @@ERROR;
PRINT 'Begin Catch';
IF @ErrorVal <> 0
BEGIN
PRINT CAST(@ErrorVal as varchar(30));
PRINT N'A error caught.';
END
END CATCH
PRINT 'done'
;
I would suggest using
TRY... CATCHinstead. This will allow you to capture and examine the error thrown.UPDATE:
I believe Martin already explained why this doesn’t work in his comments to the original question, but I’ll add a reference to the MSDN
TRY... CATCHarticle: