mercredi 30 décembre 2020

multiple conditions without using multiple if else in sql

I have to write a program in sql that has multiple conditions but i shouldn't write it with multiple if else(because of the cost that if has ) , I'm new in this field and i have no idea how else could i write it which would be better here is my sample code:

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME = 'Food_tbl')
            BEGIN
                IF NOT EXISTS (SELECT TOP 1 FID FROM dbo.Food_tbl)
                 BEGIN
                    INSERT INTO dbo.Food_tbl
                    SELECT *
                    FROM DataFoodView                       
                 END
                ELSE IF (SELECT COUNT(*) FROM dbo.Food_tbl)=20
                 BEGIN
                    PRINT N'Table Exists'
                    SELECT *
                    FROM Food_tbl
                 END
                ELSE IF (SELECT COUNT(*) FROM dbo.FoodSara_tbl)<>20
                 BEGIN
                    print N'there isnt 20'
                    INSERT INTO Food_tbl (Food_tbl.FID, Food_tbl.Fname, Food_tbl.Ftype, Food_tbl.Fcount, Food_tbl.Datetype, Food_tbl.Fdescription)
                    SELECT DataFoodView.*
                    FROM DataFoodView 
                    LEFT JOIN FoodSara_tbl ON Food_tbl.FID = DataFoodView.FID
                    WHERE Food_tbl.FID IS NULL;     
                 END
            END

PS: I have at first check if the table is exits and if it hasn't any record insert all the data, if it has 20 records show the table, if the table doesn't have 20 records find the missing data then insert that.

Aucun commentaire:

Enregistrer un commentaire