Home > Enterprise >  Set multiple variables and case statement in 1 query
Set multiple variables and case statement in 1 query

Time:03-19

I have

  • table a with columns lot and tid
  • table b with columns lot and id
  • table t with columns id and flag

One of my query set variable @ID to the below query whose flag = 'Y'

The 2nd query set variable @ID_Not_Flag to the below query whose flag <> 'Y'

Can I do the below queries (set @ID and @ID_Not_Flag) in 1 query?

SELECT @ID = a.tid          
FROM a, b, t 
WHERE b.lot = a.lot and b.id =123 and t.id = a.tid and flag = 'Y'   
SELECT @ID_Not_Flag = a.tid 
FROM a, b, t 
WHERE b.lot = a.lot and b.id =123 and t.id = a.tid and flag <> 'Y'  

Table a
lot       tid
100       1
100       2

Table b
lot       id
100       123

Table t
id        flag
1         Y
2         N

Desired result from 1 query: @ID = 1, @ID_Not_Flag = 2

The below query result in @ID = 1, @ID_Not_Flag = NULL

SELECT
@ID = (CASE WHEN flag = 'Y' THEN  a.tid END),
@ID_Not_Flag = (CASE WHEN flag <> 'Y' THEN a.tid END)
FROM a, b, t 
WHERE b.lot = a.lot and b.id =123 and t.id = a.tid
SELECT @ID,@ID_Not_Flag

Result (not correct):

ID   ID_Not_Flag
1    NULL

CodePudding user response:

You can try a pivot table. The first part of the query is just creating temp tables to hold the data.

/*CREATE TEMP TABLES*/
DECLARE @a TABLE ( lot int, tid int)
DECLARE @b TABLE ( lot int, id int)
DECLARE @t TABLE ( id int, flag VARCHAR(1))

INSERT INTO @a (lot, tid) VALUES (100, 1) , (100, 2)
INSERT INTO @b (lot, id) VALUES (100, 123)
INSERT INTO @t (id, flag) VALUES (1, 'Y') , (2, 'N')

/*QUERY*/
SELECT      [Y] [@id] ,
            [N] [@id_not_flag]
FROM (
SELECT      a.lot, a.tid, b.id , t.flag
            --,ID = (CASE WHEN flag = 'Y' THEN  a.tid END)
            --,ID_Not_Flag = (CASE WHEN flag <> 'Y' THEN a.tid END)
FROM        @a a
LEFT JOIN   @b b
                ON a.lot = b.lot
LEFT JOIN   @t t
                ON t.id = a.tid) AS Src
PIVOT (max(Src.tid) FOR flag in ([Y] , [N])) Pvt

CodePudding user response:

You can just use another join and COALESCE Example returns 1 2

DECLARE @a Table(lot INT,tid INT);
DECLARE @b Table(lot int ,id INT);
DECLARE @t Table(id INT,flag CHAR);
INSERT INTO @a(lot, tid)
values
(100, 1),
(100, 2);

INSERT INTO @b(lot, id)
values
(100, 123)

INSERT INTO @t(id, flag)
values
(1, 'Y'),
(2, 'N');

--SELECT * FROM @a;
--SELECT * FROM @b;
--SELECT * FROM @t;

DECLARE 
    @ID INT,
    @ID_Not_Flag INT;

SELECT
    @ID = COALESCE(ty.id,@ID),
    @ID_Not_Flag = COALESCE(tn.id, @ID_Not_Flag )
FROM @b AS b
INNER JOIN @a AS a ON b.lot = a.lot 
LEFT OUTER JOIN @t AS ty ON ty.id = a.tid AND ty.flag = 'Y'
LEFT OUTER JOIN @t AS tn ON tn.id = a.tid AND tn.flag = 'N'
WHERE b.id = 123;
SELECT @ID , @ID_Not_Flag ;
  • Related