简体   繁体   中英

SQL Server : getting certain table names from query

Is it possible to display just certain table names in the query:

USE [WebContact] 

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'memberEmails'

Most of the time I would need all the table names but there are curtain situations where I need just certain row names.

When I try doing the following:

USE [WebContact] 

SELECT COLUMN_NAME, ContactDateTime 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'memberEmails'

It tell me that

Invalid column name 'ContactDateTime'

even though that is one of the row names.

Is this possible to do?

if ContactDateTime is a column that you are looking for in table memberEmails then you can do this

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'memberEmails'
and COLUMN_NAME='ContactDateTime'

The column ContactDateTime may be a column in your table but it is not a column in the INFORMATION_SCHEMA.COLUMNS view.

Since it is not a column there, SQL Server is going to error out saying that it is invalid.

I think what you're trying to do is add another WHERE clause to your statement:

USE [WebContact] 
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'memberEmails'
AND [COLUMN_NAME] = 'ContactDateTime'; -- Here!

Or if you want to add multiple columns...

USE [WebContact] 
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'memberEmails'
AND [COLUMN_NAME] 
  IN ('ContactDateTime', 'column2', 'column3', ... 'column(n)'); -- Here!

Also see here for the case against using INFORMATION_SCHEMAS .

The view INFORMATION_SCHEMA.COLUMNS don't have column name ContactDateTime . Please read document first

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