SQL IF SELECT query is null then do another query

前端 未结 3 1581
时光说笑
时光说笑 2021-01-19 07:18

I have a query that regularly returns \"nothing\", and I would like to run a different query if this is the case, but I know not of the way of doing this. If anyone could be

3条回答
  •  一个人的身影
    2021-01-19 07:37

    A way you can do it is like this

    • set two variables equal to the queries you want to execute.

    • set another variable equal to the correct query when the first is not null.

    • execute that query with a stored procedure.

    STORED PROCEDURE:

    DELIMITER $$
    
    CREATE PROCEDURE `dynamic_query`(in input varchar(255))
    BEGIN
        SET @a := input;
        PREPARE stmt FROM @a;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END
    $$
    
    DELIMITER ;
    

    THE TWO SELECTS YOU WANT TO EXECUTE:

    SET @A := "SELECT * FROM  cfg_users JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId='0' AND sDisabled IS NULL AND iStatusId > 0 AND sDate = '2014-08-01' GROUP BY cfg_users.iUserId ORDER BY iStatusId, sName";
    SET @B := "your other select here";
    

    THE DEFINER TO GET THE CORRECT QUERY:

    SET @C := (
    SELECT
        CASE 
            WHEN EXISTS
                (   SELECT * 
                    FROM  cfg_users 
                    JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid 
                    WHERE iTeamId='0' 
                        AND sDisabled IS NULL 
                        AND iStatusId > 0 
                        AND sDate = '2014-08-01' 
                    GROUP BY cfg_users.iUserId 
                    ORDER BY iStatusId, sName
                )
            THEN @A
            ELSE @B
        END
    );
    

    EXECUTE THE STATEMENT:

    CALL dynamic_query(@C);
    
    • DEMO WHEN THE QUERY EXISTS
    • DEMO WHEN THE QUERY DOESN'T EXIST

提交回复
热议问题