Macros help you to change SQL statements dynamically. They allow partial replacement of the query statement by user-defined text. Macros are identified by their names which are then referred from SQL statement to replace their occurrences for associated values.
First step is to assign macros with their names and values to a dataset object.
Then modify SQL statement to include macro names into desired insertion points. Prefix each name with & ("at") sign to let MyDAC discriminate them at parse time. Resolved SQL statement will hold macro values instead of their names but at the right places of their occurrences. For example, having the following statement with the TableName macro name:
SELECT * FROM &TableName
You may later assign any actual table name to the macro value property leaving your SQL statement intact.
Query1.SQL.Text := 'SELECT * FROM &TableName'; Query1.MacroByName('TableName').Value := 'Dept'; Query1.Open;
MyDAC replaces all macro names with their values and sends SQL statement to the server when SQL execution is requested.
Note that there is a difference between using TMacro AsString and Value properties. If you set macro with the AsString property, it will be quoted. For example, the following statements will result in the same result Query1.SQL property value.
Query1.MacroByName('StringMacro').Value := '''A string'''; Query1.MacroByName('StringMacro').AsString := 'A string';
Macros can be especially useful in scripts that perform similar operations on different objects. You can use macros that will be replaced with an object name. It allows you to have the same script text and to change only macro values. For example, the following is a script that creates a new user account and grants required privileges.
Script1.SQL.Add('CREATE USER &Username IDENTIFIED BY &Password;'); Script1.SQL.Add('GRANT &Privileges TO &Username;');
To execute the script for another user you do not have to change the script SQL property, you can just set required macro values.
You may also consider using macros to construct adaptable conditions in WHERE clauses of your statements.