In this post, we will discuss writing a transact SQL query to list all the tables, views, store procedures in a SQL server database and it is also a very common SQL server interview question.
Within SQL server management studio, We can use Object Explorer to list all the tables that belong to a specific database.
For example, if we have to find the tables that belong to the Demo database, we can simply expand the database within object explorer and then expand the tables folder.
And then you can find the list of tables that belong to the Demo database
On the other hand, if I have to write a query to achieve the same, then we can make use of three system views.
We can either SYSOBJECTS, SYS.TABLES or INFORMATION_SCHEMA.TABLES views.
The SYSOBJECTS view is available and SQL Server 2000, 2005, and 2008.
Whereas SYS.TABLES and INFORMATION_SCHEMA.TABLES Views are available in SQL Server 2005 and 2008 and later version only, they are not available in SQL server 2000.
Now let’s see how to use SYSOBJECTS view to retrieve all the tables that are present in the Demo database.
Now, when I execute the below query, I get all the objects that are present in the Demo database. SQL Server can have different types of objects like tables, views, function stored procedures.
Select * from [SYSOBJECTS]
So SYSOBJECTS view contains all those objects. Now, if I just want the tables, then I filter on Xtype column.
When I execute the query, notice that I get the tables that are present in the Demo database.
Select * from [SYSOBJECTS] where XTYPE='U'
Now Xtype, what does ‘U’ mean? ‘U’means user table. So where do I have this list? Actually, you can visit MSDN link for all possible Xtype column values and what they represent.
MSDN-sys.sysobjects (Transact-SQL)
fn stands for a scalar function So if you want all scalar functions then you simply, filter on that
Select * from [SYSOBJECTS] where XTYPE=’fn’
if I want stored procedures, the Xtype for that is sp, I get all the stored procedures. Similarly, if you want just views then replace XTYPE with V.
Now, if I want to know what are the different types of objects are available in the Demo database, I can find out that by issuing a distinct query.
Select Distinct XTYPE from [SYSOBJECTS]
Now let’s see how to use the SYS.TABLES.
You simply say Select * from SYS.TABLES. That’s going to return all the tables in our Demo database.
Select * from SYS.TABLES
Similarly, if you want views, you can simply use, SYS.views. And if you want procedures, you simply use SYS.procedures. So I see all the stored procedures within the Demo database.
Select * from SYS.views Select * from SYS.procedures
Now, let us see how to use INFORMATION_SCHEMA.TABLES View,
Select * from INFORMATION_SCHEMA.TABLES is going to give us all the tables as well as views
So if you want just the tables, then filter on the table type column.
Similarly, if you want just the views, you can use INFORMATION_SCHEMA.VIEWS.
Select * from INFORMATION_SCHEMA.VIEWS
Now, if you want stored procedures, you can use INFORMATION_SCHEMA.ROUTINES
Select * from INFORMATION_SCHEMA.ROUTINES
Thank you for reading. Have a great day.
The post How to Get the list of all Tables, Views, Stored procedures appeared first on Software Development | Programming Tutorials.
Read More Articles
- Linq to SQL Group by and Sum in Select | Linq To SQL Group By and Sum
- How send an HTTP POST request to a server from Excel using VBA?
- What is Difference between where and having clauses in SQL server
- How to Use EXCEPT Operator with an example in Sql
- How to use merge statement in the SQL server
- How to write Re-runnable SQL server query
- How to create Cursor in sql server with example
- How to generate random data in sql server for performance testing
- How to write subquery in select statement in Sql
- How to Log record changes in SQL server in an audit table
- MAX in SQLSERVER
- Fill Factor for Datawarehouse - SQL Server
- SQL - Matching two rows from multiple columns in one table to 1 row in another table.
- SQL:listing duplicate records from multiple join statements ?
- Using a User Defined Datatype as a Stored Procedure parameter?
- Summary calculation for different times
- How to check existence of a table from a different sql db?
- What is the reason one sql server process needs "RangeS-U" lock though it has "X" lock on the same table-key
- MSSQL & SQL data type alternatives?
- How to find adjacent values in a column based on another column value in Sql
- How to get monthly report in Pivot format in SQL?
- Check file exists with T-SQL openrowset
- Log Trigger (BEFORE UPDATE) - SQL Server
- How to replace a NULL value in SQL table?
- Does it mean anything if port 1434 UDP is enabled?
- Joining Data Between 2 SQL Tables
- Merge row values into a CSV (a.k.a GROUP_CONCAT for SQL Server)
- SQL Server Partial Database Backup (excluding some tables)
- SQL Server trigger with based on two columns on a table
- SQL combining Union and Except
- sorting columns with in a row SQlite
- Methods of Deleting Duplicates in SQL Server with SSDT
- Create a mapping between two tables
- Updating views with VBA-ADO in SQL Server requires UPDATE privileges on underlying table (MS Access / VBA)
- How do you get a node that contains a child node with a given value in an XML document using sql server?
- Compile single string from sql results
- SequelizeJs Associations in NodeJs for MsSql
- SQL - How to count yes and no items
- Concatenated string in column alias
- how to perform Two select query in one stored procedure in sql server
- Merge two sql queries with if condition
- SQL server Sub string
- Can I use the result of a SUM function in the WHERE clause of MSSQL?
- UTC time to Local Time Zone(Central Time) Conversion MS SQL Sever
- Is there any way to reference CDC objects in a SSDT database project?
- SQL Server date configuration error
- Delete duplicate rows
- Query count with multiple table group by month return zero if month is null
- IDENTITY Column reset numbering
- Trim inside the Scalar UDF with stuff sql
- Auto increment the column value by 1 conditionally in select query in sql
- Stored procedure to find time difference between all the apps in the table
- Select Max Number From Multiple Tables
- Linq filter issue involving a varchar(1) field
- Insert into Access from SQL Server
- Return Distinct Rows That Contain The Same Value/Character In SQL
- Get Reference of ForeignKey by SMO
- Combining 2 date fields for a conditional split
- SQL Server: how import XML with node's fields
- TSQL Operators IN vs INNER JOIN
- How would I obtain the primary key of a newly inserted table row in a SQL Database from Access VBA?
- Enforcing referential integrity from one table to any table
- Lambda expression Linq-to-SQL get from record 5 to 10
- How do I include the newlines from syscomments in SQL Server?
- Why does comparing a SQL date variable to null behave in this way?
- Generate XML comments with SQL FOR XML statement
- Sort Asc and desc in the same column
- In SQL Server, is there a way to return a single row of data as a 2 column table?
- MSSQL 2016 Package execution failed | SSIS error: Index was out of range
- Attempting to optimize sql query
- How to copy data from one table to another table based on criteria
- Function for Using Now instead of GetDate in SQL Server 2012
- SQL server agent not reporting failure from uncaught exception in PowerShell script
- Microsoft SQL - Identify duplicates and assign a unique identifier
- What should we prefer to use Stored Proc or Prepared statements
- Insert Trigger with check option on multiple tables view
- How to get around unique key constraint when updating via Entity Framework (using dbcontext.SaveChanges())
- How to get Identity value from SQL server after insert record
- Use T-SQL custom function in C# code
- How can I transfer data from a SQL table to an Oracle table?
- Singular method to retrieve data from SQL Server for various stored procedures, how to handle parameters?
- C# CLR throws security exception unless marked as UNSAFE
- How can i evaluate this query?
- How to read the value of XMLColumn from SQL Server table
- SQL Query based on rules
- SQL Server - remove left part of string before a specific character
- how to show the split the days of between two months
- Update a table from two comma separated parameter as input
- Error in SQLServer: Subquery returned more than 1 value
- SQL Conditional Case
- Clustered and nonclustered index - SQL Server and Oracle?
- TSQL Dynamic Pivot with two alternating columns
- Why can't I specify column width in MS SQL?
- Connect to SQL Server on Windows from WSL2 with pyodbc - Connection Timeout
- Wrong value from DropDownList, SQL Server
- Decimal(19,4) or Decimal(19.2) - which should I use?
- How to debug merge in SQL Server?
- Encrypt an sql script to be run on a server
- best way to catch database constraint errors
- Sql server Db Mail which can send mail for two or more queries
- Good practices of SQL Server: nvarchar(max) performance
- Making automatic True False Generator
- Collation conflict in SQL
- Error assigning value using TOP 1
- Sql Server replication requires the actual server name to make a connection to the server
- ISNULL, COALESCE functions
- Selecting a column name defined by a calculated day of the week in a function
- Entity Framework query throws 'async error' after many requests
- How do I get just the date when using MSSQL GetDate()?
- Convert to HH:MM in SQL Server
- Record counts where column contains char(x)
- What is the use of a transaction log on a read-only database?
- ASP Classic SQL query to get cumulative ammounts per day
- Get Data in one SQL query
- Calculating total minutes of an employee
- Kubernetes SQL Server or Azure SQL Server PaaS
- Bringing SQL Server filegroups online
- Is there any way to create a temporary table using subquery in SQL?
- SSRS result different from SSMS result with the same query
- Duplicate key with SYSDATETIME() default on DATETIME2 column
- Insert random Data content in SQL Server 2008
- Which algorithm is used for Checksum(), Binary_Checksum() and CHECKSUM_AVG() function in SQL Server?
- What is the suggested approach to Syncing/Backing up/Restoring from SQL Server 2008 to SQL Server 2005
- how to transform '01 Oct 2015' into a valid date format, IF language = GERMAN
- Display Boolean Field in Visual Studio Report Designer
- T-SQL version of MySQLs CURTIME()
- Creating jobs in SQL Server 2008
- SQL : Grouping the Data
- Extract first and last name from email address. Microsoft SQL Server
- I get an error for inserting data into SQL Server via VB.Net
- Is there a linux command line tool for MSSQL/SQLSRV that would allow creating dumps and importing them?
- Filling the ID column of a table NOT using a cursor
- Unique random integer as primary key ID instead of auto increment
- Aggregating one column based on the distinct value of another column
- I have a column of dates in varchar and i need to convert to date
- Filtering data from the previous day using DateTime values
- Get all records arranged by maximum number of columns matched
- How we can use keyboard Shortcut key like CTRL+F3 in sql server?
- Adding to two tables, can't add foreign key to second table
- stored procedure wrong in profiler
- Edit a dtsx through SSMS
- Use SQL geography field to initialize .NET DbGeography object
- MSSQL Timeout error
- Microsoft SQL server: copy table from linked server to current database using a stored procedure
- How to determine which SQL entries are missing after querying?
- Alternative to nested select statements
- Why is there a Foreign Key conflict
- SQL Order by posts containing occurences of string in another table
- The multi-part identifier could not be bound
- How to select using Left Function with a condition in SQL Server?
- what is use of (..) double dot in sql server stored procedure
- Select syntax inside WHERE
- need empty row in output between rows with data Report Builder 3.0 T-SQL
- JBoss cluster with Apache, AJP change's date eventualy
- how to return result of select while trying a safe generic stored procedure using sp_executesql
- How to send email alert when 2 SELECT COUNT statements from 2 different servers is not equal?
- SQL Server equivalent of Oracle’s “when no data found” exception
- Use value of 'AS ColumnName' later in query
- Pivot in sql server: Vertical to Horizontal data
- TSQL query for Week Comparison