MySQL Select If Table Exists

后端 未结 1 1696
名媛妹妹
名媛妹妹 2020-12-11 10:21

I need to run a count query on a table but only if that table exists,

SELECT 
CASE WHEN (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA =          


        
相关标签:
1条回答
  • 2020-12-11 10:50

    You can try this :

           SET @val := CASE (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'DATABASENAME' AND TABLE_NAME = 'testtable')
               WHEN 0 THEN 0
               ELSE (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'DATABASENAME' AND TABLE_NAME = 'testtable')
    
    END;
            SELECT @val;
    

    It will return 0, if there is no such table and if such table exists , it will return the count, it may be better if you take it into function.

    0 讨论(0)
提交回复
热议问题