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 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.
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.
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.
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.
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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With