alexistkd
alexistkd

Reputation: 898

Use if else sql statement with two selects

Currently I have the following SQL query

DECLARE @UgpEntry VARCHAR(50)

SET @t1.UgpEntry = (SELECT @UgpEntry = t1.UgpEntry from OITM t1)

IF (@UgpEntry = -1)

SELECT
t1.ItemCode as sapitemcode
     , t1.CodeBars as Barcode
     , t1.ItemName as description
     ,LEFT(t1.ItemName,20) as short_description
     , 
           (select max(p.Price)
        from ITM1 p 
        where p.ItemCode = t1.ItemCode 
          and p.PriceList = 1) as [price_1]
     , CASE t1.VatGourpSa when 'V0' THEN 4 when 'V1' THEN 1 WHEN 'V2' THEN 2 WHEN 'V3' THEN 3 END as TaxCode,t1.U_GRUPOA, t1.U_GRUPOB, t1.U_GRUPOC, t1.UgpEntry

FROM OITM t1
WHERE t1.ItemCode='00004' and t1.UgpEntry = -1
 
ELSE

SELECT t1.ItemCode as sapitemcode
     , t1.CodeBars as Barcode
     , t1.ItemName as description
     ,LEFT(t1.ItemName,20) as short_description
     , (select max(p.Price)
        from ITM9 p 
        where p.ItemCode = t1.ItemCode 
          and p.UomEntry = 1) as [price_1],

           (select max(p.Price)
        from ITM1 p 
        where p.ItemCode = t1.ItemCode 
          and p.PriceList = 1) as [preciocaja]
     , CASE t1.VatGourpSa when 'V0' THEN 4 when 'V1' THEN 1 WHEN 'V2' THEN 2 WHEN 'V3' THEN 3 END as TaxCode,t1.U_GRUPOA, t1.U_GRUPOB, t1.U_GRUPOC, t1.UgpEntry

FROM OITM t1
WHERE t1.ItemCode='v6p' and t1.UgpEntry > -1

What I'm trying to do:

  1. If this column t1.UgpEntry from OITM table (already exists and have data) is equal to -1 then run the first query.

  2. Else run the second query.

What am I doing wrong? i need to run one or the other select, depending on the IF statement

example: this record have a column named UgpEntry = -1

enter image description here

enter image description here this record have UgpEntry = 5 and have another columns

i think i have this var wrong IF (@UgpEntry = -1) as it should be the column from OITM but not sure how to use that column as IF statement

Upvotes: 0

Views: 53

Answers (1)

DeMaki
DeMaki

Reputation: 491

The layout of your IF statement is correct. Just make sure the query to set @UgpEntry returns a single result.

DECLARE @UgpEntry VARCHAR(50)

SELECT @UgpEntry = UgpEntry FROM OITM WHERE [enter your condition]

IF (@UgpEntry = -1)
    [remaining logic from your original post]

Upvotes: 1

Related Questions