How to find error on script using Microsoft.SqlServer.TransactSql.ScriptDom

172 Views Asked by At

I have a SQL script X Select top 1 * from table. I use MicrosoftSql.Smo to check script has error or not. The letter X is incorrect for SQL script. But it cannot find the error in the script and evaluates as true. How can I solve this problem. Instead of using GetTokenStream, I also used Parse method. Nothing has been changed.

IList<ParseError> parseErrors;
TSql140Parser tsqlParser = new TSql140Parser(true);
IList<TSqlTokenStream> tStream;
using (StringReader stringReader = new StringReader(script))
            {
                tStream= (TSqlFragment)tsqlParser.GetTokenStream(stringReader, out parseErrors);
            }
if (parseErrors.Count > 0)
{
   var retMessage = string.Empty;
   foreach (var error in parseErrors)
   {
     throw new Exception("error in script")
   }
}
return (TSqlScript)fragment;
1

There are 1 best solutions below

1
Martin Smith On

This isn't a grammar error.

The script

X Select top 1 * from [table]

is just treated the same as

EXEC X;

Select top 1 * from [table];

SQL Server allows the term EXEC to be omitted in the first statement in a batch so it just interprets it as you trying to execute a stored procedure called X