Thursday, September 25, 2008

Retrieve Fields, Tables and SPs [LEVEL::BASIC]


Here are some simple SQL-Script (T-SQL) to retrieve:

1. List of fields of a table
2. List of user tables in a database
3. List of stored procedures in a database

NOTE: In (3), SUBSTRING([name], 1, 3) <> 'sp_' is set to filter system stored procedures (we already know that we should avoid naming stored procedures starting with "sp_" because stored procedures starting with it make the SQL Server first scan the list of system stored procedures.

1.
private const string FIELD_LIST_QUERY = "SELECT DISTINCT syscolumns.name [Name], syscolumns.length Size, ISNULL(systypes.name, 'UNKNOWN') Type, syscolumns.colid Position, syscolumns.isnullable FROM syscolumns INNER JOIN sysobjects ON syscolumns.id = sysobjects.id LEFT OUTER JOIN systypes ON syscolumns.type = systypes.type WHERE (systypes.usertype IS NULL OR systypes.usertype in (1,2,7,10,13,15,16,19,28,12)) AND sysobjects.name = '{0}' ORDER BY 4;";


2.
const string TABLE_NAME_QUERY = "SELECT [name] FROM sys.objects WHERE [type] = 'U' AND is_ms_shipped = 0 AND [name] <> 'sysdiagrams' ORDER BY 1;";

3.
const string SP_NAME_QUERY = "SELECT [name] FROM sys.objects WHERE [type] = 'P' AND SUBSTRING([name], 1, 3) <> 'sp_' ORDER BY 1;";

No comments:

Post a Comment