I'm trying to use Microsoft.SqlServer.TransactSql.ScriptDom to check that an expression is a scalar constant.
Here is such an expression:
DATEADD(YEAR, -21, CURRENT_TIMESTAMP)
Here is not such an expression:
DATEADD(YEAR, -21, DateOfBirth)
It is not a constant because it references the column DateOfBirth.
How can I determine this?
What I didn't expect -- and why I've run into trouble -- is that Microsoft.SqlServer.TransactSql.ScriptDom thinks that YEAR is a ColumnReferenceExpression.
(too long for comment)
ScriptDomdoes not compile, just parses and treats all "strange names" as possible column names, e.g. inIF (MAGICNAME = 0)will be detected a "column" namedMAGICNAME. If you want more, you have to add more intelligence to this process by yourself.This can be done by making additional visitor classes to be used as nested parsers. And by storing lists of "known magic words relevant to specific cases". Which in given case may lead to code which:
In this approach a specific visitor for
DATEADD(or all the date handling functions) might have the list of wordsYEAR,MONTHand so on to change the understanding of first argument from "possible column" to "known static magic word".Given task can hardly be accomplished in general, for any possible case, however it looks like many cases can be handled correctly. An idea is to implement "duck typing" approach: