Code to validate SQL Scripts

前端 未结 4 851
挽巷
挽巷 2020-11-28 08:19

How can I validate sql scripts before executing them using .net 2.0 and c#?

If the sql is not valid I want to return error rows.

4条回答
  •  猫巷女王i
    2020-11-28 08:58

    SSMS has a way of doing this.

    If you use the SQL Profiler you will see that it executes SET PARSEONLY ON, then the SQL and then SET PARSEONLY OFF and any errors are risen without compiling or executing the query.

    SET PARSEONLY ON;
    SELECT * FROM Table; --Query To Parse
    SET PARSEONLY OFF; 
    

    PARSEONLY

    I have never tried this from c# but I see no reason why it should not work, it works from SSMS after all.

    As Martin Smith points out in the comments you can use SET NOEXEC ON

    MSDN says the following about both commands.

    When SET NOEXEC is ON, SQL Server compiles each batch of Transact-SQL statements but does not execute them. When SET NOEXEC is OFF, all batches are executed after compilation.

    When SET PARSEONLY is ON, SQL Server only parses the statement. When SET PARSEONLY is OFF, SQL Server compiles and executes the statement.

    That indicates that NOEXEC will also compile the query where PARSEONLY will not. So NOEXEC may catch errors that PARSEONLY does not. The usage is the same.

    SET NOEXEC ON;
    SELECT * FROM Table; --Query To Parse
    SET NOEXEC OFF; 
    

    NOEXEC

提交回复
热议问题