How can I programmatically check (parse) the validity of a TSQL statement?

后端 未结 7 435
礼貌的吻别
礼貌的吻别 2020-12-04 10:25

I\'m trying to make my integration tests more idempotent. One idea was to execute rollback after every test, the other idea was to some how programatically parse the text,

相关标签:
7条回答
  • 2020-12-04 10:33

    I think the command you are looking for is SET NOEXEC ON. If you set this for your connection, the queries will be parsed but will not be executed. Another option would be SET PARSEONLY ON, but I'm honestly not sure what the difference between the two really is.

    0 讨论(0)
  • 2020-12-04 10:34

    Use the following query

    SET PARSEONLY ON
    --Your query here
    SET PARSEONLY OFF
    
    0 讨论(0)
  • 2020-12-04 10:54

    Really it depends upon the purpose of the tests.

    The most reliable way would be to use the rollback after every test if your statements lend themselves to that (aren't too heavy weight to make it viable).

    I have done this in the past and have been glad to be notified of runtime issues that I wouldn't have caught any other way.

    0 讨论(0)
  • 2020-12-04 10:57

    SQL Server 2012 can parse your syntax, procedures and tables with the following system procedures and functions:

    • sp_describe_first_result_set (Transact-SQL)
    • sp_describe_undeclared_parameters (Transact-SQL)
    • sys.dm_exec_describe_first_result_set (Transact-SQL)
    • sys.dm_exec_describe_first_result_set_for_object (Transact-SQL)

    They are supposedly replacing "SET FMTONLY".

    I have tested them and they work a lot better than "SET NOEXEC ON" and "SET PARSEONLY ON"

    Examples:

    Will not throw an error:

    sp_describe_undeclared_parameters
        @tsql = N'SELECT object_id, name, type_desc FROM sys.indexes;'
    

    Will correctly throw an error ("SET NOEXEC" and "SET PARSEONLY" do not throw an error in this case):

    sp_describe_undeclared_parameters 
      @tsql = N'SELECT object_id, name, type_desc FROM sys.indexes;SELECT object_id, name, type_desc FROM sys.NOTaTABLE;'
    
    0 讨论(0)
  • 2020-12-04 10:57

    VSTSDBPro has a query parser you can access programmatically: http://blogs.msdn.com/b/gertd/archive/2008/08/21/getting-to-the-crown-jewels.aspx

    0 讨论(0)
  • 2020-12-04 10:58

    SET PARSEONLY : Examines the syntax of each Transact-SQL statement and returns any error messages without compiling or executing the statement.

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