Thursday, August 4, 2016

Dynamic View Creation in Teradata based on a Table List

A common approach (and best practice) for building a data warehouse on Teradata is to build an access layer of 1-1 views on top of the physical tables in your data warehouse.  The primary purpose of this access layer is to ensure that DW queries do not lock rows which could halt ETL processes.  The following statement will generate the view statements for any tables specified by the following parameters:

$DBName$
$TableList$

SELECT
   DatabaseName
  ,TableName
  ,TRIM(TRAILING ',' FROM (XMLAGG(TRIM(Columnname (varchar(100)))|| ','
                           ORDER BY ColumnId) (VARCHAR(4000)))) column_list
  , 'REPLACE VIEW $VIEWDBNAME$.' || trim(TABLENAME) || ' AS (LOCKING ROW FOR ACCESS SELECT ' || column_list || ' FROM ' || trim(databasename) || '.' || trim(tablename) || ');' viewscript
FROM dbc.columnsv
where DatabaseName = '$DBName$' and TABLENAME in ('$TableList$')
GROUP BY 1,2;