How can I check the SQL syntax in a .sql file?

后端 未结 7 1231
走了就别回头了
走了就别回头了 2021-02-03 23:20

How can I check the SQL syntax in a .sql file?

7条回答
  •  不知归路
    2021-02-03 23:45

    TLDR:

    >awk '{print "EXPLAIN " $0}' statements.sql | mysql --force -u user -p database | grep "ERROR"
    

    Strangely, mysql does not have a built-in switch for this, but you can check syntax by adding the EXPLAIN statement in front of your queries.

    If you have a statements.sql file with each statement on one line, prepend EXPLAIN in front of all lines with:

    >awk '{print "EXPLAIN " $0}' statements.sql > check.sql
    

    You can then run the statements with the mysql command-line tool and use --force to have it continue on error. It will print an error for any statements with incorrect syntax.

    >mysql --force -u user -p database < check.sql
    

    Or to only view the lines with errors:

    >mysql --force -u user -p database < check.sql | grep "ERROR"
    

    You can do all of this on one line without creating an intermediate file:

    >awk '{print "EXPLAIN " $0}' statements.sql | mysql --force -u user -p database | grep "ERROR"
    

提交回复
热议问题