Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : SELECT from sys.tables and sys.views

Tags:

sql

sql-server

The below SQL seems to be working, but I am wondering if there is a better way to write this. I am trying to select all views and tables with a specific name. There should only be one return value if a match is found.

SELECT DISTINCT name 
FROM sys.tables 
WHERE name = 'MyName'  

UNION ALL

SELECT DISTINCT name 
FROM sys.views 
WHERE name = 'MyName'
like image 719
Chris Lombardi Avatar asked Sep 01 '17 17:09

Chris Lombardi


People also ask

Which is faster select from table or view?

there is no difference. A view is just a stored query which can be referred to in sql queries as though they are tables. Note that this does not apply to materialized views. A view is only a query stored in the data dictionary: it is not going to make your query run faster or slower.

Can we use select * In view?

If you change the structure of any tables in the underlying view, select * may break any applications that rely on the columns being in a specific order etc. It's generally accepted that doing select * anywhere, not just in view definitions, is bad practice.

Can you select from a view in SQL?

A view is actually a composition of a table in the form of a predefined SQL query. A view can contain all rows of a table or select rows from a table.

What is System_type_id in SYS columns?

sys.columns.system_type_id = sys.types.user_type_id For a built-in type, it returns the built-in type. For a user-defined type, it returns the built-in base type. This might make sense, for example, if you want to get all varchar columns, including all user-defined columns based on varchar.


2 Answers

There's another view which may help you - it is a single view which contains both tables and views. Performance wise, my single-table query performs better, though you'll only notice on a database with a very large number of tables. I modified your query for this purpose.

SELECT 
    DISTINCT NAME 
FROM SYS.OBJECTS
WHERE TYPE IN ('U','V')
AND NAME= 'MYNAME'

U = User Table
V = View

like image 146
Eli Avatar answered Oct 14 '22 14:10

Eli


There is INFORMATION_SCHEMA exposed in SQL Server. Kindly note that taking TABLE_NAME here disregards the schema of the table.

More DMVs here

So, do check out these Dynamic Management Views (DMVs) separately first.

SELECT * FROM INFORMATION_SCHEMA.TABLES

SELECT * FROM INFORMATION_SCHEMA.VIEWS

You can use

SELECT 
    distinct TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'MyName'  

UNION ALL

SELECT 
    distinct TABLE_NAME 
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME= 'MyName'
like image 43
Amit Kumar Singh Avatar answered Oct 14 '22 13:10

Amit Kumar Singh