Question : IF STATEMENT

Hi All,

Please help me with a query regarding the IF statement in a Stored Procedure.

Bascially I want to check a parameter passed to the SP if there is a value assigned to it I want to do one thing if not I want to no nothing.

The code is as follows:

@Instruction      int(4),
@iID                int(4),
@iActive                int(1) = NULL

IF @Instruction = 2
BEGIN
           SELECT
                       myTable.myName
           FROM
                      myTable
           WHERE
                      myTable.myID=@iID
           IF @iActive<>NULL                                          
           BEGIN
                     AND myActive=@iActive
           END
END

Code End

The problem is with the code:
           IF @iActive<>NULL                                          
           BEGIN
                     AND myActive=@iActive
           END
SQL-server complains about syntax error. Any ideas?

Thanks,
Indod.

Answer : IF STATEMENT

Where are 2 ways of doing this

1. Dynamic
2. IF statement

1.
Declare varchar(255) variable, test for your condition, concantenate and do adynamic EXEC

DECLARE @fActive varchar(255)

IF @iActive is not null
    SELECT @fActive = "AND myActive=" + @iActive
   

EXEC("SELECT myTable.myName FROM myTable WHERE myTable.myID= " + @iID + @fActive)


2.
IF @iActive is null
BEGIN
          SELECT
                       myTable.myName
          FROM
                     myTable
          WHERE
                      myTable.myID=@iID
END
ELSE
BEGIN
          SELECT
                       myTable.myName
          FROM
                     myTable
          WHERE
                      myTable.myID=@iID
          AND myActive=@iActive
          END
END
Random Solutions  
 
programming4us programming4us