Best pattern for Constants in SQL?

后端 未结 4 1193
心在旅途
心在旅途 2020-12-15 10:23

I have seen several patterns used to \'overcome\' the lack of constants in SQL Server, but none of them seem to satisfy both performance and readability / maintainability co

4条回答
  •  长情又很酷
    2020-12-15 11:06

    Hard coded. With SQL performance trumps maintainability.

    The consequences in the execution plan between using a constant that the optimizer can inspect at plan generation time vs. using any form of indirection (UDF, JOIN, sub-query) are often dramatic. SQL 'compilation' is an extraordinary process (in the sense that is not 'ordinary' like say IL code generation) in as the result is determined not only by the language construct being compiled (ie. the actual text of the query) but also by the data schema (existing indexes) and actual data in those indexes (statistics). When a hard coded value is used, the optimizer can give a better plan because it can actually check the value against the index statistics and get an estimate of the result.

    Another consideration is that a SQL application is not code only, but by a large margin is code and data. 'Refactoring' a SQL program is ... different. Where in a C# program one can change a constant or enum, recompile and happily run the application, in SQL one cannot do so because the value is likely present in millions of records in the database and changing the constant value implies also changing GBs of data, often online while new operations occur.

    Just because the value is hard-coded in the queries and procedures seen by the server does not necessarily mean the value has to be hard coded in the original project source code. There are various code generation tools that can take care of this. Consider something as trivial as leveraging the sqlcmd scripting variables:

    defines.sql:

    :setvar STATUS_LOADED 87
    

    somesource.sql:

    :r defines.sql
    SELECT ... FROM [Table] WHERE StatusId = $(STATUS_LOADED);
    

    someothersource.sql:

    :r defines.sql
    UPDATE [Table] SET StatusId = $(STATUS_LOADED) WHERE ...;
    

提交回复
热议问题