SQL-File Technology for Transact-SQL

This article is about so-called statically parameterized SQL language, suggesting use of enhanced SQL-code residing in specially organized project of SQL-files located in corresponding tree of subfolders. Connected SQL-files (static scripts) are stored together with simple definition files, of values named as SQL-settings, containing parameters for the static SQL. (It’s a short formulation.) My realized idea was to pick up a set of tools as an alternative IDE able for operation with parameterized SQL in files: panel with text editor, file tree, commands etc. Along with this — to develop additional building utilities, in order to support in a certain degree an alternative approach for database interaction from perspective of constructing and/or programming (from developer’s or administrator’s machine, client of SQL Server), that is based primarily on some editor of source text in files (as the central location of code sources). One of the way for such approach is to use old-styled traditional file commander, which contains simple but universal text editor, with possibility to compose command line scripts (not only sole SQL) for different cases where complex processing is needed. Also (as one of intentions of SQL-file creation) writing of some auxiliary SQL-code (suite of helpers in form of a library) was made.

My idea is named SQL-file technology (for MSSQL and T-SQL). In spite of a modest implementation of the SQL-file I think that the idea has certain value and sense.

I. What is SQL-file technology (approximate definition)

There is an official utility from Microsoft, SQLCMD. It is what SQL-file technology is similar to, at the first view. Indeed it is strongly based on this powerful and helpful file oriented utility. At time of SQL-file creation (from its early versions) it was not reasonable to organize a fully separated really autonomous script processor (at client side), whereas it’s desirable to have a good integration and compatibility with other MSSQL features in your approach. SQLCMD is a base file translator (dev.time client utility for the SQL Server), but by no means it’s not a complete program environment, it doesn’t suggest something like file project integration etc. It does support environment variables (properties) as file script parameters (SQLCMD insertions to SQL-code like $(<VariableName>)), but there is no effective and unified approach where we can configure a complex collection of properties like we can do it for instance in “.props”-file(s) (XML, MSBUILD). From the other side SQL Server Management Studio (which is the default IDE) is not also so well for advanced working (programming) with files. This graphical console does not indeed work with files but instead performs SQL-script corrections in the database (which is the primary script location for this dev.tool). So scripts in files are supported rather as illusion in such GUI (DB-console). A lack in client tools exists for working (programming) in DB with files, as primary storage of SQL scripts. SQL-file technology is a modest attempt to create (organize) corresponding client constituent (tools/utilities) as additional part of DBMS, for administrator and/or developer, that is specially oriented to operate with SQL source code in files (as primary location of SQL-scripts).

Numerous technical details are included into this article: file names, variable names, micro-fragments of configurations etc. It doesn’t mean all such things have to be clear for the reader in one moment. The details are relatively understandable, their purpose here is to meet you with a spirit of applied techniques and to introduce partially some approaches. For normal acquaintance a set of references exist, web-links to corresponding resource containing a lot of named screenshots and minimal textual information. (Normal article perception depends on applied images from that pages.)

SQL-files are applied (translated) to the database so to speak from a location of source code in file project (in grouping folder): (1) In the editor; (2) By activation of single file from list (file items) in UI (file commander or from another panel); (3) From specially organized command line script (e.g. complex translation in several steps). File groups may be processed (translated to database) in one step (as a single operation): (1) One chosen SQL-file (plus some additional special files); (2) Simple group of scripts, such as “*.sql” (with possibility to specify some item names in “$sql_order.list”, to correct the order of file sequence for the processing); (3) Subdirectories by name pattern (all at once), plus local SQL-files (like “*.sql”), that is a big group (for single translation, is performed in one connection). Each script in SQL-file project is located properly in the tree, correct location of source file is important here.

The main tool in this program environment is Far Manager 3 (widely known and powerful file commander), it is a rich console-mode application, and this is here the primary IDE (prompt editor and command console). Some other tools are possible to use with SQL-file: (1) Windows Explorer (as scarce command panel); (2) SSMS official IDE (with some constraints); (3) Autonomous external source text editor (GUI).

SQL-file technology, $SQLTRANS-utility, SQLAUX scripting lib.

SQL-file technology suggests some components for advanced programming in MSSQL database:

  1. $SQLTRANS utility (see: $SqlTrans command, $SQLTRANS syntax print), which is inalienable part of SQL-file, it is based on SQLCMD (official command line utility, that is equipped with preprocessor from MS), and SqlCatPP.exe (this subprogram concatenates source SQL files for the translation, also it has some functions of simple preprocessor);
  2. SQLAUX library settings for preprocessor (helpful keywords and constants for so-called Enhanced T-SQL), are accessed as $(<VariableName>_AUX), i.e. macro helpers, see: #SQL_extensions.AUX.sql, #Constants.AUX.sql, #Data_types.AUX.sql (SQLAUX API – headers files, in code view);
  3. SQLAUX library objects in DB (functions and stored procedures: [AUX:<ObjectName>], database helpers), see: SQLAUX programmatics and tables (listing);
  4. Collection of templates and samples (SQL, CMD, TXT, $sql_order.list), this is needed to derive new SQL-file project (configured folder with connected files).

All my utilities (EXE) are supported with corresponding source code to be able to rebuild them. Small projects (C#, C++) are located under “HandicraftSDK\Auxiliary programs (sources)” folder, in download package(s). The sources are provided with multiple build commands (as CMD-files in project root) with corresponding operation names. So it’s not difficult to adjust such compilation if some corrections will be needed. (Also official build tools are required then).

CMD-processor’s role

CMD-processor (Command Prompt, legacy command-line interpreter in MS Windows) plays an important role in this “handicraft” implementation of SQL-file. The batches are well adopted for SQL-file (they are equipped with abundant set of auxiliary subroutines). This handicraft IDE is native in CMD and console. Specially applied command line format acts as a glue between SQL-settings (environmet variables), SQL-scripts and command scripts (SQL-translation scenarious). This is not a modern way, but it works stably. Another known command line processors may not occur so much successive in this mission. (To make user experience more attractive, invention of a special script/configuration format is necessary for SQL-project and SQL-commands construction, with desirable support of general scripting possibilities, like JS-engine out of browser, to process instructions in imperative style.)

Resuming the above, SQL-file technology is an approach to organize SQL-file project, in order to code inside database in so-called Enhanced T-SQL, with SQL-settings of different levels (SQLAUX macro keywords; SQL-project central settings; modified SQL-settings of file subtree), with possibility to invoke some additional functions and procedures of universal character (general helpers in DB). This technology implementation (for MSSQL) is targeted for time of development and/or administration. This means, that your project environment is not directly for user application. Of cause the application may access all the objects in the database (SP, functions, views, tables, triggers) that are created with help of the SQL-file. But application queries with embedding of SQL-settings (via the preprocessor, in Enhanced T-SQL) are not possible in this implementation (were not realized in my Handicraft-CODE).

$SQLTRANS utility is the key subprogram in the SQL-file. It is written in CMD and acts as intermediary between SqlCatPP.exe (internal subprogram that is SQL-scripts concatenator and also additional preprocessor) and SQLCMD.EXE (powerful command line utility from MS), which interacts with SQL Server. The simplest way to translate SQL-file (execute its content on SQL Server) is following command: $sqltrans "<Base name>.sql", or $sqltrans "<Base name>.sql" "<Base name>.txt" (to save SQL execution report into corresponding TXT). There are many variants of invocation. ($sqltrans-command without parameters prints its syntax, shows some hints about how to call it with files.)

Preprocessor function in SqlCatPP

There is own simple preprocessor in SqlCatPP subprogram (with two different modes), besides functionality of the SQLCMD (that is the official PP from MS). So-called strong preprocessing mode exists in SQL-file, supported by SqlCatPP.exe (in addition to so-called preprocessor weak mode, which in its turn is used in order to eliminate incorrectness of error diagnostics connected with ingenious removal of original source line with :SetVar directive, by the SQLCMD). Strong preprocessing mode is intended for the sake of possibility to reconstruct preprocessing result (preprocessed and concatenated scripts) in order to transfer (e.g. send by the e-mail) such target script to so-called database dealer. DB-dealer (human who operates in DB) applies SQL-scripts received from the developer, executes them on the target DB. He or she is not able to prepare developer’s environments (like SQL-project does at developer’s machine). All he or she is needed is to have already prepared target SQL-script (as result of strong preprocessing under influence of SQL-project environment at computer of the developer). For instance, SQLAUX library itself is exported to the outside through “sqlaux_library.sql” file, compound script from “HandicraftSDK\SQL\SQLAUX\Source\$OUTPUT” folder, 173 DB-objects are destroyed-created in it (it can be executed from the SSMS, with default settings). However, strong preprocessing mode should be used with care (only if it’s necessary). It has not been tested enough and it may pose some risk. (As a matter of fact it’s hard to achieve exactly same behavior in SqlCatPP as MS-preprocessor has in SQLCMD, regarding interpreting of comments, literals, PP-directives etc.)

Dual character of organization of CMD-batches for SQL-commands

Most part of SQL-commands (CMD-scripts) supports so-called dual invocation. In case of normal call the console is not usually closed at the end until you press correspondent key(s). Also at the beginning, request of confirmation to proceed the command there may be appeared. If the command fails (some error is encountered), it normally prints error message (often colored in red) and plays bell-signal. This is a normal behaviour for the error. In case of so-called nested invocation (it is applied in complex batch like following: call $SQLTRANS.cmd … or some other stock or user defined commands), in such a call the above mentioned measures are avoided: no confirmation, no completion pause, no bell-signal in case of error. If you click on a command (properly named command file) in Windows Explorer, then standalone console appears, you are able to read the output (text and messages printed to the console) when the command succeeds or fails. This is due to special measures inherent to normal call. In case of the nested call root command is probably invoked in normal way (so it’s all right with confirmation, pause, messages etc.). Invocation duality is helpful therefore. Not only SQL-commands, C#-project building commands (containing MSBUILD / dotnet build etc.) and others, many CMD-batches are organized in dual invocation manner.

Such is a rough sketch of my production around SQL Server. Its essential constituent is original program environment at client-side, albeit it is rather an integration with its key component, official utilities: SQLCMD, BCP (key programs of MSSQL Command Line Utilities). The other part is T-SQL scripting library named SQLAUX, that is a server-side targeted component.

Console natural environment (i.e. pseudographical commander) and only some GUIs

SQL-file primary IDE is severe. Text editor in Far Manager does not provide you with function of code autocompletion. Though Intellisence for SQL is available in SSMS, if you run IDE-process via SSMS.cmd starter, command file in SQL-project root (folder). But restriction exists for SSMS+Environment. Variables from SQL-setting CMDs then are frozen for whole session of the IDE (Ssms.exe, OS process).

Instead, Far editor is prompt and native for programming in SQL-file. It is suitable for creation/editing of SQL script as well as for editing of CMD and many other file types. Code coloring is nice (dark theme in VS Code looks similarly). Vertical block selection exists in the editor, characters of OEM code page are displayed properly, including pseudographics, series of unicode encodings is supported well, etc. Far Manager is valuable because it is universal enough.

Anyway SQL-commands (project CMDs) are autonomous, such CMD may be launched in separated console window (via <Shift+Enter> in Far Manager or from folder of the Windows Explorer).

II. Simple script (Hello) sample at Handicraft-CODE pages

There is a modest web-resource named Handicraft-CODE. It is dedicated to so-called handicraft programming style, special autonomous manner in software development. SQL-file technology is a partition of Handicraft-SDK, which in its turn is one of two large-scale divisions in Handicraft-CODE public pages. At the last part of this article there is a list of useful Handicraft links connected to SQL-file technology. The central SQL-file page is: https://handicraft.remelias.ru/sdk/sql_file.html.
Lack of description texts have to be compensated by numerous screenshots (scripts, settings, configurations, execution output, result sets etc.).
Simple script (Hello) sample path in the SDK:
“HandicraftSDK\SQL\Programming samples (SQL-file)\Simple script (Hello)”.

Some of the demonstrated screenshots (not those from the Simple script) may contain elements of Russian localization (if were made in the Russian locale on the author’s machine or by some other reasons).
SQL-file was tested under the following system locales (default code pages for single-byte apps):
1) English (USA), i.e. CP-1252 (Latin alphabet) / OEM: CP437;
2) Russian (Russia), i.e. CP-1251 (Cyrillic script) / OEM: CP866.
For the other system languages (default locales) SQL-translation date-time stamp may be formed with some mistakes, probably in its date part. I’m sorry! (Sometimes it may be non-critical because time order inside the day is preserved.) The following variables can help for the other locales (different from the two above): YYYY_START_IN_DATE (optional), MM_START_IN_DATE, DD_START_IN_DATE (zero-based positions have to be specified through the variables).

Simple script (Hello) is that from where screenshot pages begin. In the download packages it is one of six simple examples, six subfolders of “Programming samples (SQL-file)” folder. The sample consists of 12 files of following types (extensions): SQL, CMD, TXT, and one of the files is without the extension: %simple_script%; it is so-called SQL microscript, is included by “:r”-directive as a head of “simple_script.sql”, which is here a main SQL-script. The files are dependent one from the other. So indeed this simple script is not trivial, several features are gathered in it. The first of three T-SQL batches, portions of instructions continuing to GO-separator (but not including it), do following:

The first batch is in %simple_script% file, it prints report header as text message: *** SIMPLE SCRIPT (<date and time>): ***. The other two batches are in simple_script.sql.

The second batch produces five primitive result sets, they are:

  1. General greeting (message);
  2. Extended greeting, in Russian;
  3. $(str_UnicodeString)-property value (from SQL-project settings) that are letters from modern Greek alphabet (24 capitals);
  4. SQLAUX system variables (output of three names-values is performed): is_sqlaux_imported, sql_translation_timestamp_aux, sql_settings_script_aux;
  5. sql_translation_dir_aux variable view (file translation folder path, is ended with backslash).

The third batch prints output termination decorator: — — — (three m-dashes through the space character). That’s all (this is a simple script).

The pictures are on the first page with the screenshots (11 images under the first 4 captions-groups, SEE ALL 11 PICTURES).

SQL-file screenshots-1:

  1. Simple script (Hello) / T-SQL in files (simple_script.sql and %simple_script% in SQL-project directory);
  2. Simple script settings (SQL-file project defs: $sql_settings.cmd, @simple_script.cmd);
  3. Simple script output (TXT-report in simple_script.txt, Console, SSMS);
  4. Simple script run (elementary simple_script.cmd and complex run_simple_script.cmd).


  1. !ReadMe.txt — simple explanation of sample program intentions;
  2. $ide_root.sql — it is intended for SSMS.cmd to designate project root folder for the IDE;
  3. $sql_settings.cmd — predefined settings batch name, is activated by $SQLTRANS, it attaches SQLAUX import definitions and project definitions from @simple_script.cmd (conventional name);
  4. $sql_settings.sql.bak — alternative way for specification of SQL-settings (it is not compatible with SSMS, that is why it’s not recommended), $sql_settings.sql is inserted at the beginning of any SQL-translation (automatically by the $SQLTRANS), if it is not blocked by $sql_settings_script variable (hyphen value ‘-’ in the SQLAUX) or if it is referenced in $sql_settings.cmd (via $sql_settings_script variable);
  5. %simple_script% — this microscript is included in the first line of simple_script.sql (:r "%simple_script%"), its purpose is to print a caption of the report;
  6. @simple_script.cmd — project definitions, SQL-settings in the project root, imported by $sql_settings.cmd (some of them may be overridden in subfolders if they are), this is conventional name for SQL-settings non-trivial configuration in UTF-8 (text content is stored without signature, i.e. no BOM-prefix, but CmdCpAuto plugin for Far Manager “understands” the special filename);
  7. exec_no_confirm.cmd — as opposed to simple_script.cmd which is in a normal mode, this command (batch-file) avoids involving of user confirmation step (there is nothing unsafe in simple_script.sql), SQL-output goes to the console;
  8. exec_simple_script.cmd — normal execution with SQL-output (result print) to the console;
  9. run_simple_script.cmd — minimal example of so-called complex command (SQL-output goes to the console);
  10. simple_script.cmd — the most natural command form for saving SQL-ouput to corresponding TXT-report, with obligatory user confirmation (in general SQL-script may be dangerous for the database);
  11. simple_script.sql — main SQL-script producing compound report;
  12. simple_script.txt — TXT-report (SQL-output as result of simple_script.sql execution);
  13. SSMS.cmd — so-called IDE-starter, it prepares SQL-project environment (SQL-settings as environment variables) and launches the IDE process (Ssms.exe), $ide_root.sql is then opened in SQL Server Management Studio (as single SQL-file tab).

Main block for exception capturing, script embracing macros: $(BEGIN_AUX), $(END_AUX)

Batch content in SQL-file is usually wrapped between $(BEGIN_AUX) and $(END_AUX). Only one such protection code block per T-SQL batch is permissible. In T-SQL language we have a strange control flow by default (without exception catching) that obliges us to check @@ERROR variable almost after each instruction, elsewhere there is no guarantee that execution is interrupted correctly (goes to a panic branch) if SQL-instruction fails. This is a legacy behaviour (it’s a default mode of control flow in T-SQL) in SQL Server, inherited from the very earliest versions. This fact (unreliable or inconvenient control flow in T-SQL, in default mode) was a main reason (among other serious circumstances) due to SQL-file approach was invented, that then allowed to use parameterized SQL files with special macro keywords (folded sequences of instructions for repeating use). Below you can see how main error protection is unfolded. If an error occurs inside a block it is caught as exception to be thrown at the end of the catch section, after possible rollback of explicitly opened transaction (if there is) initiated earlier by $(BEGIN_TRANSACTION_AUX) macro in the block.


: : : : :


begin begin try set xact_abort off; set ansi_nulls,ansi_null_dflt_on,quoted_identifier,arithabort,nocount on; set implicit_transactions off; declare @initial_tran_count_aux int, @is_local_tran_open_aux bit; select @initial_tran_count_aux=@@trancount, @is_local_tran_open_aux=0; end try begin catch throw; end catch; begin try
: : : : :
if @is_local_tran_open_aux=1 raiserror ('Not closed local transaction was detected, previously opened by BEGIN_TRANSACTION_AUX macro.',11,1); end try begin catch if @is_local_tran_open_aux=1 and (@@trancount>@initial_tran_count_aux or xact_state()=-1) rollback transaction; set @is_local_tran_open_aux=0; throw; end catch; end


begin begin try set xact_abort off; set ansi_nulls,ansi_null_dflt_on,quoted_identifier,arithabort,nocount on; set implicit_transactions off; declare @initial_tran_count_aux int, @is_local_tran_open_aux bit; select @initial_tran_count_aux=@@trancount, @is_local_tran_open_aux=0; end try begin catch throw; end catch; begin try
: : : : :
if @is_local_tran_open_aux=1 raiserror (‘Not closed local transaction was detected, previously opened by BEGIN_TRANSACTION_AUX macro.’,11,1); end try begin catch if @is_local_tran_open_aux=1 and (@@trancount>@initial_tran_count_aux or xact_state()=-1) rollback transaction; set @is_local_tran_open_aux=0; throw; end catch; end

GO-separator is excluded by SQLCMD. $(BEGIN_AUX) and $(END_AUX) insertions are unfolded to the above instruction sequences by SQLCMD, or may be processed by SqlCatPP if strong preprocessing mode is switched on (set SqlCatPP.ProcessDirectives=1 in $sql_settings.cmd, but this possibility should be used with caution).

Also look at this SQL-code as part of SP (shown in SSMS): $(BEGIN_AUX) macro in DB (preprocessing result).

Simple script (Hello) sample is one of six elementary examples provided with SQL-file. The others are: “GUID-list generation”, “Lists downloading (sys-info)”, “Nested transaction test”, “Trigger test”, “Uploading to DB (used buildings)”, in “Programming samples (SQL-file)” folder. They are also provided with corresponding minimal instructions in “!ReadMe.txt”. All sample projects (above mentioned and others) are listed in “SQL-projects-sum.txt”, in root folder of the Handicraft Toolkit. As for the Simple script (Hello), this SQL-project does not have subfolders. For the majority of other samples, they have. SQL-settings in subfolder are inherited from the above level, by specially organized $sql_settings.cmd (it usually attaches settings from the upper directory level). Some new variables may be added, some existed values can be corrected. Even in named user commands (batches) we can specify something peculiar. Usually utility behaviour is configured there, by special variables like $sqltrans.*, SqlToCsvExport.* (base setting name is implied in place of the asterisk). For instance, in exec_simple_script.cmd: rem set $sqltrans.ContinueOnBatchError=1. (If you uncomment this line, all three GO-batches in the Simple script will probably work in spite of possible batch errors.)

III. What is a gain from SQL-file use?

SQL-file technology can be applied with your scripts with maximal intensity or in some insignificant degree. You may only use file translation or other utilities (like $SQLUPLOAD or $SqlToCsvExp). For instance, somebody may decide to depend on helpful macros from SQLAUX library (its unfoldable keywords), but it doesn’t mean you need to use its database helper objects (i.e. SQLAUX SP, DB-function etc.). If you, for instance, have a folder with SQL-files, it is enough to place $sql_settings.cmd in it to be able to translate them by $SQLTRANS, by one or all together (however processing of partial file group is available only through subfolders). You even may be able to translate your files without simple $sql_settings.cmd, if you define some system or user variables: $sql_server, $sql_database (or, if needed, $sql_user, $sql_password_var and correspondingly named variable as SQL-password container). Temporary variables specification is possible in Far Manager, in its command prompt or via user menu, for OS process of the commander. Thus, user CMD-batches are not strictly obligated in SQL-file. Anyway use of $sql_settings.cmd is recommended. The other very recommended thing is not to avoid SQLAUX library import, which is performed in $sql_settings.cmd (it also imports @<project_name>.cmd, SQL-settings in UTF-8). (This is similarly to some important include-files in C-language or in RC-file, not for the sake of function headers but mainly in order to have required preprocessor-level defs.)

Far Manager keyboard shortcuts

Far Manager keyboard shortcuts are listed below, for translation of single file with “.sql”-extension.

Keyboard shortcuts for SQL-translation from Far Manager panels (assigned in Main menu :: Commands :: File associations :: A file mask or several file masks: *.sql):

  • <Enter> — initiate SQL-translation in the commander window (i.e. output to parent console), with safety confirmation;
  • <Ctrl+PageDown> — initiate SQL-translation in standalone window (maximized console), without safety confirmation.

Keyboard shortcuts for SQL-translation in Far Manager embedded editor (activated by LUA-macros Editor_CtrlEnter.lua and Editor_CtrlF12.lua):

  • <Ctrl+Enter> — save SQL-file, initiate SQL-translation in the commander window (i.e. output to parent console), with safety confirmation;
  • <Ctrl+F12> — save SQL-file, initiate SQL-translation in standalone window (maximized console), without safety confirmation.

Far Manager keyboard shortcuts for SQL-command initiation, for execution of “<Command name>.cmd”:

  • <Enter> or <MouseLeft::DoubleClick> — execute CMD in parent console window of the commander;
  • <Shift+Enter> or <Shift + MouseLeft::DoubleClick> — execute CMD in standalone console window.

Project folder in Windows Explorer may be opened from the Far Manager by <Shift+Enter> or <Shift + MouseLeft::DoubleClick>, on “..”-sign (the upper dir.).

Also Editor_CtrlR.lua macro is intended for possibility to quickly comment command line with “rem ” (without quotes), in the embedded editor.


= I.=
Utility application for needs in DB-administration

= II.=
Developer’s use for creation of application (service) part in DB: SP, scalar and table functions, views, triggers etc; such objects are called programmatics in SQL-file terminology (i.e. objects with some activity, and even views)

IV. CMD is well suitable for lightweight superstructure with user commands and settings.

It sounds strange, but in spite of its legacy character CMD-processor is not easily replaceable in some cases. All that is needed for SQL-file intention is that, that CMD does naturally. I.e.: decorated output, invocation of another batch, satisfactory error checking (even bell signal is enabled there), simple parameters support, organization of subroutines etc. (Missing functionality has been filled in by corresponding tiny subprograms, EXE from “CMD-utilities\Assemblies” subfolder, e.g. $CONFIRMPAUSE and $TYPEINCOLOR commands.)

Even UTF-8 is partially available, in SQL-settings CMD “@<project_name>.cmd”, it is used there without BOM-prefix. (The other CMDs are in OEM code-page, like CP437, CP866.) Special Far Manager plugin CmdCpAuto (little subprogram with source-code: “HandicraftSDK\Auxiliary programs (sources)\Far plugins\CmdCpAuto”, “HandicraftSDK\Utilities\Far plugins\CmdCpAuto plugin, build 100 (Far v3)”) is used with SQL-file to switch code-page automatically for some file extensions and file names, when you open embedded file editor (normally by F4 key).

CMD is not perfect of cause, but it is viable with SQL-file. (This is a handicraft technology implementation.)

V. Multiplatform settings represent a powerful approach for programming in two or more languages if you are able to access the configured values with help of language preprocessor or in a task for source code generation.

It could be fine to be able to specify universal preprocessor definitions targeted more than one language, so-called multilingual preprocessor. Some values (especially constants) may be needed simultaneously: in the database (in SQL objects stored in DB), in server process’s EXE (in some language with OOP), and at the client side on user’s computer (another language with OOP). For example, we want to know string length capacities, minimums and maximums etc., they are required at several sides (in DB, in server process, in user input filed etc.). Imagine yourself, that we describe a lot of values (sizes and not only), dependent one on another, and all these names and values become wonderfully available as code autocompletion function in every of the above mentioned three languages, with some little correspondent differences, with possibility of the conditional compilation etc. It could be a magic glue with a static character (i.e. for just before the compilation/interpretation stage) for uniting of very different environments, such fabulous preprocessor. But the reality is a contrary as a rule and we do not have such static joining (except some rare situations like in C/C++).

SQL-settings defined in “@<project_name>.cmd” are mainly for parameterized SQL files, but not only. In extremis some important settings can be used (involved into) in source code generation via corresponding building task. In MyFlat app. and BookRegistry app. WriteLinesToFile MSBUILD-task performs such generation of C# class, with valuable constants for use in related projects (classes: MyFlat.DB.DBConstants, BookRegistry.Server.DB.DBConstants and BookRegistry.Client.DB.DBConstants, in DBConstants.auto.cs). Scripts: generate_metadata.cmd, generate_metadata.props, generate_metadata.targets and DBConstants.cs.props (in “SQL (DB-modelling)” SQL-project folder). This is a labour-intensive organization of minimal static integration of two programming languages (T-SQL/C#).

VI. SQL-file technology at Handicraft-CODE web-pages

To understand the subject the following web-pages exist in https://handicraft.remelias.ru/ domain:

In other web-domains (outside Handicraft-CODE, there is a little about SQL-file):
Client-Server WASM-Application In C#, TypeScript And Transact-SQL — my article at C# Corner, it is about experimental program named BookRegistry app., that is built with help of SQL-file technology.

VII. My work, universal constructor named SQL-file

SQL-file technology is, of cause, experimental production. Never the less this approach has been proved (as earlier product incarnation) at least in two real-world databases, in a system, intended for calculation of payment for a series of communal and other living services (processed in flat owner database).

SQL-file app. as conceptual transformation of SQL-file technology

Potentially, another technology, SQL-file app. (i.e. proposed name) can be created as analogical approach, for writing of application queries (not SP and functions in DB) in parameterized Enhanced T-SQL (app.time queries), and in the same time which have to be suitable also for a dev.time queries (in developer’s environment). This day we only have the handicraft implementation of the SQL-file technology (for MSSQL). This is in fact peculiar constructor for dev.time only, for determining of settings for parameterized SQL-files, and for building of our own SQL-translation commands (adopted scripts for command line processor).

However I believe that the way with parameterized SQL files is potentially effective, and it is not impossible to transform simple SQL-file into something more flexible, such as the SQL-file app. Also I suppose there is no good way to globally unify SQL-languages (contradictory idea), but there is an approach for partial unification of SQL dialects, which have to be based (I propose) on identical query headers (for all supported SQL dialects) and unique implementations of query bodies for the each dialect. These are examples of relatively unified query headers (in some approximation): GetServiceUser.sql (side-by-side files: SQL), UpdateBook.sql (side-by-side files: SQL), with result @Status and @Message output parameters (@RStatus and @RMessage names in new unpublished version of corresponding DB-library), returnable integer value, specification of one or more result sets (if provided) etc.

Such an application (DB accessing program) may be organized for interaction with SQL-queries by dividing each query into two heterogeneous parts, that is formed as so-called side-by-side files. For instance: C# and SQL (“<QueryName>.cs” from the client-side and “<QueryName>.sql” from the server-side). Only fundamental DB-mapping functionality is required, to transmit SQL-query input data (like parameters) and to obtain result data from SQL-queries (returnable integer value, output parameters, result sets). No big ORM is needed because this idea is contrary to classical ORM concept. It’s like writing code for OS kernel-mode in C, providing the application with user mode library in C# and/or C++ to access the driver. Here I imply so-called paradigm of IRPs (Input/Output Request Packets, in KMDF/WDK). Special auxiliary tools will be needed of cause for effectiveness of such development (with dual SQL-queries), in order to automatically generate pieces of source code for access to “Database IRP”: SQL/C#/… (Examples in my experiments are labour-intensive.)

Also it seems to be that some modifications in DBMS are required if we want to have a fluent support of efficient client queries from the server side (by providing a worth-while analog of temporary stored procedure as prepared client query, from corresponding SQL-file or piece of SQL-code from the client). Moving this way we (or somebody) can invent a lot of useful and entertaining.

At the end

Sincerely it is not likely you’ll suddenly have an admiration examining SQL-file. It is because it may be looking knotty at the first view and also giving you a doubtful gain. My opinion is that it’s not too complex and is worthwhile, at least from experimental perspective. I’ve created this constructor and it have worked a lot for me. But general idea is more valuable than particular implementation. I hope it’ll be interesting for you to acquaint yourself with SQL-file technology.

Blog author

Sergei Y.Kitáev
Author of the Handicraft-CODE resource
https://handicraft.remelias.ru/ (page passage, root)
https://handicraft.remelias.ru/sdk/sql_file.html (to SQL-file)