Sei sulla pagina 1di 2

HOW TO: Find all the tables and columns in selected database in SQL Server - #SQLQUERY

#SQLTIPS #SQLQUERY #SQLINTERVIEWQUESTIONS #SQL2005 #SQLSERVER In case when we do not have direct access to database server & cannot look in to the database we can take help of SysObjects, SysColumns, SysTypes tables of SQL Server 2005. These tables stores the information about each tables and columns and their data types. Using this tables you can write the query to find out all the tables and columns in selected database. Below is the query that gives you all the table and columns with data types and length. SELECT SO.[Name] as TableName, SC.[Name] as ColumnName, ST.[Name] As DataType, SC.[Length] As Length FROM SysObjects SO INNER JOIN SysColumns SC ON SO.[Id] = SC.[Id] INNER JOIN SysTypes ST ON ST.[xtype] = SC.[xtype] WHERE SO.[type] = 'U' ORDER BY SO.[Name] Type column of SysObjects table represent the different objects available in database (like Table,Trigger,Stored Procedures etc.). Below list explains the different values of Type columns. * C: Check constraint * D: Default constraint * F: Foreign Key constraint * L: Log * P: Stored procedure * PK: Primary Key constraint * RF: Replication Filter stored procedure * S: System table * TR: Trigger * U: User table * UQ: Unique constraint * V: View * X: Extended stored procedure For more detail refer SysObjects - and SysColumns. You can change the condition in WHERE clause to get different objects.

The query shown below displays all the stored procedures in selected database. SELECT SysObjects.[Name] as SPName, SysColumns.[Name] as SPParameters, SysTypes.[Name] As DataType, SysColumns.[Length] As Length, SysObjects.[Crdate] As CreatedDate FROM SysObjects INNER JOIN SysColumns ON SysObjects.[Id] = SysColumns.[Id] INNER JOIN SysTypes ON SysTypes.[xtype] = SysColumns.[xtype] WHERE SysObjects.[type] = 'P' ORDER BY SysObjects.[Name] Similarly you can use INFORMATION_SCHEMA.Columns for getting similar result - gives you all the table and columns with data types and length. SELECT TABLE_CATALOG As DatabaseName, TABLE_NAME As TableName, COLUMN_NAME As ColumnName, DATA_TYPE As DataType, CHARACTER_MAXIMUM_LENGTH As Length FROM INFORMATION_SCHEMA.Columns

Potrebbero piacerti anche