简体   繁体   中英

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

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'

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'

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

If you had a table and a view with the same name but different schemas, you would get back a result set with two rows -- this does not meet your requirements. Instead, use just 'Union' and remove distinct from the individual queries.

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

UNION 

SELECT 
    name 
FROM sys.views 
WHERE name= 'MyName'

Rather that doing a DISTINCT, I'd rather see everything that meets the filter criteria. Adding a couple more columns will allow you to actually identify the data that's being returned.

SELECT 
    o.object_id,
    ObjectName = CONCAT(s.name, ',', o.name),
    ObjectType = o.type_desc
FROM
    sys.objects o
    JOIN sys.schemas s
        ON o.schema_id = s.schema_id
WHERE 
    o.type IN ('U', 'V')
    AND o.name = 'MyName';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM