HomeActive Query Builder - Query analysis and modificationProgrammatic modification of SQL queriesHow to rename a table in the query programmatically

2.7. How to rename a table in the query programmatically

To rename a table in the query you may simply iterate through the datasources (learn basics in the Understanding complex SQL query structure representation and Enumeration of data sources and joins in a sub-query articles) and rename them, but the fine point is that you should call the QueryBuilder.Query.NotifySQLUpdatedRecursive() method to apply your changes to the query text.

Dictionary renamedDataSources = new Dictionary();
renamedDataSources.Add("old","new");

queryBuilder1.BeginUpdate();
try
{
    UnionSubQuery firstSelect = queryBuilder1.Query.FirstSelect();
    System.Collections.ArrayList dataSourcesArrayList = new System.Collections.ArrayList();

    firstSelect.FromClause.GetDatasources(dataSourcesArrayList);
    foreach (DataSourceObject dataSourceObject in dataSourcesArrayList)
    {
        SQLDatabaseObject databaseObject = dataSourceObject.DatabaseObject;
        string originalDataSourceName = databaseObject.QualifiedNameWithoutQuotes;

        if (renamedDataSources.ContainsKey(originalDataSourceName))
        {
            databaseObject.RemoveLastName();
            databaseObject.AddName(renamedDataSources[originalDataSourceName]);
        }
    }
    queryBuilder1.Query.NotifySQLUpdatedRecursive();
}
finally
{
    queryBuilder1.EndUpdate();
}

This page was: Helpful | Not Helpful