If conditional in SQL Script for Mysql

后端 未结 2 1788
野趣味
野趣味 2020-12-16 15:00

In a sql script that does sequential execution, is there a way one can introduce an IF THEN ELSE conditional to control the flow of query execution?

I happened to ru

2条回答
  •  难免孤独
    2020-12-16 15:42

    After doing some research I think I may have found a way to work around this. I was looking for a way to verify if a script had already executed against a target database. This will be primarily for version control of my databases. I have a table created to keep track of the scripts that have been executed and wanted some flow inside my scripts to check that table first before execution. While I have not completely solved the problem yet I have created a simple script that basically does what I need, I just need to wrap the DDL into the selects based on the value of the variables.

    step 1 - Setup a bit variable to hold the result step 2 - do your select and set the variable if the result is found step 3 - Do what you need to do on false result step 4 - Do what you need to do on true result

    Here is the example script

    set @schemachangeid = 0;

    select @schemachangeid := 1 from SchemaChangeLog where scriptname = '1_create_tables.sql';

    select 'scriptalreadyran' from dual where @schemachangeid = 1;

    select 'scriptnotran' from dual where @schemachangeid = 0;

    I also recognize this is an old thread but maybe this will help someone out there trying to do this kind of thing outside of a stored procedure like me.

提交回复
热议问题