views:

697

answers:

3

I'd need to know how to parse a query to know if it is well build before executing it. If the parsing is correct then execute it, if not discard it.

I haven't been able to accomplish this using SET NOEXEC, SET PARSEONLY, TRY/CATCH.

I m using dynamic sql inside a loop. Sometimes the dynamic sql is incorrect not for my fault but for the information existing in the database. For this reason I would like to parse it before execution.

+1  A: 

Try using SET FMTONLY ON and SET FMTONLY OFF.

SET PARSEONLY ON your code SET PARSEONLY OFF should work for most though.

MSDN FMTONLY

Shane O'Grady
+1  A: 

This might be possible with some sp_executesql trickery:

-- The query you would like to parse
declare @sql nvarchar(max)
set @sql = 'select 1'

declare @testsql nvarchar(max)
declare @result int
set @testsql = N'set parseonly on; ' + @sql
exec @result = sp_executesql @testsql

-- If it worked, execute it
if @result = 0
    begin
    exec sp_executesql @sql
    end

If I use an incorrect query, like 'salact 1', the @result value is nonzero.

The TRY/CATCH does not seem to play well with sp_executesql, so I'm checking the return value instead.

Andomar
A: 

What are you trying to accomplish?

As stated before, T-SQL won't compile unless the query is parseable.

If you just want to have a way to verify that the query is fine (ex. to verify that you didn't forget the where statement or so) then maybe the showplan will help you

set showplan_xml on

this will tell the sql server to just parse the query (the query itself is never executed) and return the execution plan for it. It is mostly used for performance issues, but can also be used as a pointer in case something is really incorrect with the query.

Jimmy Stenke