Thursday, 13 June 2013

MSSQL - Query Templates - usage of system tables

Sometimes you have to find all the tables (their names), which have the field with the specified name.
The easiest way to do this is through queries to the system tables.
Because this task occurs frequently, I have created T-SQL template:
  1. -- Find Tables by Column-Name
  2. USE <DataBaseName, sysname, tempdb>;
  3.  
  4. SELECT
  5. [SCHEMA] = schemas.name,
  6. [TABLE] = tables.name,
  7. [COLUMN] = columns.name
  8. FROM
  9. sys.schemas
  10. INNER JOIN sys.tables ON
  11. schemas.schema_id = tables.schema_id
  12. INNER JOIN sys.columns ON
  13. tables.object_id = columns.object_id
  14. WHERE
  15. schemas.name IN ('<schema_name, sysname, dbo>')
  16. AND
  17. tables.name LIKE '<TableNamePattern, sysname, %>'
  18. AND
  19. columns.name LIKE '<ColumnNamePattern, sysname, %_ID>'
  20. ORDER BY
  21. [SCHEMA],
  22. [TABLE],
  23. [COLUMN];
Save this template to your templates folder with for example following name:
"SysTables - Sch-Tb-Clm". After replacing of placeholders you will see something like this:
  1. -- Find Dimension-Tables with Code-Columns
  2. USE AdventureWorksDW2008R2;
  3.  
  4. SELECT
  5. [SCHEMA] = schemas.name,
  6. [TABLE] = tables.name,
  7. [COLUMN] = columns.name
  8. FROM
  9. sys.schemas
  10. INNER JOIN sys.tables ON
  11. schemas.schema_id = tables.schema_id
  12. INNER JOIN sys.columns ON
  13. tables.object_id = columns.object_id
  14. WHERE
  15. schemas.name IN ('dbo')
  16. AND
  17. tables.name LIKE 'Dim%'
  18. AND
  19. columns.name LIKE '%Code'
  20. ORDER BY
  21. [SCHEMA],
  22. [TABLE],
  23. [COLUMN];

The result of execution will be something like this:

No comments:

Post a Comment

Note: only a member of this blog may post a comment.