Help with IF in SQL SERVER Stored Procedure

can someone help me with building IF in stored procedure on sql server.

Basically, I have a simple stored procedure, but now I need to pass a new input parameter, which depends if it is true. I pass the value of D, and if its value is false, I pass the value of A. But this change is in the middle of the subquery .. let me explain ... here is the stored procedure. basically, if I send True for ReturnOldStatus, I execute the subquery ItemStatus = 'D', and if it is false, then I pass ItemStatus = 'A'

CREATE PROCEDURE [dbo].[MyTempStoredProc]
(
 @IdOffice                                 Int,
 @ReturnOldStatus                           bit
)
AS
BEGIN
   SET NOCOUNT ON;
   SELECT * FROM Offices

   WHERE
      IdOffice = @IdOffice  

      AND (V.OffType NOT IN (
                        SELECT *  FROM MiscOff 
                        WHERE
ItemStatus= 'D') // This needs to be ItemStatus ='A' if FALSE is passed in on the input param

Any ideas?

thanks

+3
source share
3 answers

:

    declare @itemStatus varchar(1);
    if (@inputParam = 'FALSE')
    begin
        set @itemStatus = 'A'
    end
    else
        set @itemStatus = 'D'

   SELECT * FROM Offices
   WHERE
          IdOffice = @IdOffice      
          AND (V.OffType NOT IN (
                   SELECT *  FROM MiscOff 
                   WHERE ItemStatus= @itemStatus) 
              )

T-Sql , ...

+5

if:

IF @ReturnOldStatus = 0
    BEGIN
        --Some statements
    END
ELSE
    BEGIN
        --Some other statements
    END
+2

I think this will be enough for your problem. If not, review the DECLARE / SET instructions in TSQL.

CREATE PROCEDURE [dbo].[MyTempStoredProc] 
    (@IdOffice Int, 
     @ReturnOldStatus bit ) 
AS BEGIN 
    SET NOCOUNT ON; 

    SELECT * FROM Offices 
    WHERE IdOffice = @IdOffice  
          AND (V.OffType NOT IN (SELECT * FROM MiscOff 
                                 WHERE (ItemStatus= 'D' AND @ReturnOldStatus = 1)
                                         OR
                                       (ItemStatus= 'A' AND @ReturnOldStatus = 0) 
                                )
+1
source

Source: https://habr.com/ru/post/1708041/


All Articles