Skip to content
Advertisement

How to solve this error “ERROR 102 sql state 420000” which comes up when I try to create this procedure

I am trying to create a procedure which check whether the number entered (as a nvarchar type) already exists or not. If it exists then the updation takes place, else an error is thrown out to the user. But am not able to create the procedure because as soon as I execute the command ERROR 102/156 SQL STATE 42000 comes up.

CREATE PROCEDURE UpdateAWBUnique
(
    @AWB as nvarchar,
    @Internal as nvarchar
)
AS
BEGIN
    SET NOCOUNT ON
    if((SELECT count(*) From Def_tab WHERE AWB=@AWB) == 0) 
    BEGIN
        UPDATE Def_tab SET AWB= @AWB
        where Internal=@Internal
    END
    ELSE
    BEGIN
        PRINT 'Already Exits'
    END
END
GO

FYI I use Microsoft SQL Server. How to clear this error and create the procedure?

Advertisement

Answer

Conditionally UPDATE and see if any changes happened

    UPDATE Def_tab 
    SET AWB = @AWB
    WHERE Internal = @Internal 
         AND NOT EXISTS (SELECT 1 FROM Def_tab t WHERE t.AWB= @AWB)
    IF (@@ROWCOUNT = 0)
        PRINT 'Already Exits'

Otherwise in a concurrent environment something may happen between

if((SELECT count(*) From Def_tab WHERE AWB=@AWB) == 0) 

and

BEGIN
    UPDATE Def_tab SET AWB= @AWB

renderring the if check useless

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement