Our team aims to develop applications with DDD approach and we're trying to avoid putting any logic into database. So in database schema we usually use integers for enumeration values, uniqueidentifiers for GUIDs , etc.But sometimes we still have tasks that require some logic to be written in plain SQL - usually it is data migration required by schema changes, some data related bug fixes and export to data warehouse to build some BI reporting on top of it. We've been using several approaches on writing sql scripts in a maintainable way, but not all of them are always cool.
A bit better approach is to create sql variables: Still this approach has some drawbacks. If you need to structure your SQL code in several files then you'll have to declare same variables again and again per each file. Also sometimes for debug purposes one need to execute only particular statement in a big file. This may be not that easy if variables are declared in the beginning and you need to execute only something in the middle of the file
Let's consider example with users of different types. User type is an enumeration, that is stored in integer column.
Let's write some queries that will return only Administrator users only.
The easiest way is just to inline integer values into sql script:
This approach is OK for trivial scripts that do not require support. Once you get a query referencing several enums and constants it will become complex and easy to make and error.
The easiest way is just to inline integer values into sql script:
This approach is OK for trivial scripts that do not require support. Once you get a query referencing several enums and constants it will become complex and easy to make and error.
A bit better approach is to create sql variables: Still this approach has some drawbacks. If you need to structure your SQL code in several files then you'll have to declare same variables again and again per each file. Also sometimes for debug purposes one need to execute only particular statement in a big file. This may be not that easy if variables are declared in the beginning and you need to execute only something in the middle of the file
The approach that our team came up with during a huge data migration task is to use constant tables:
All constant tables do not mess with application tables since they are defined in a separate schema. All constants are defined only once and may be referenced without additional declarations. Also a big benefit is that you get compilation an intelli-sence support for you constants in SQL :)
No comments:
Post a Comment