SQL Server How can specific columns be excluded from results when selecting from INFORMATION_SCHEMA?

iswrvxsc  于 2023-04-04  发布在  其他
关注(0)|答案(3)|浏览(117)

Here is my previous question on how to iterate a string in SQL Server:

Now how can I specifically select column names? here is my code for selecting columns:

SELECT 'Field '+CAST(ROW_NUMBER() OVER (ORDER BY ordinal_position) AS varchar(5))+': ' + 
COLUMN_NAME
FROM information_schema.columns 
WHERE table_Name = 'SystemDefined' and table_schema = 'schemaAsset'

Here is the output:

Field 1: Asset_No
Field 2: AssetCategory
Field 3: AssetClassification
Field 4: PurchaseType
Field 5: Department
Field 6: RespPerson
Field 7: Status
Field 8: Location

This the output I want when selecting specific column names:

Field 1: Asset_No
Field 2: AssetCategory
Field 3: AssetClassification
Field 4: PurchaseType
Field 5: Department
Field 6: RespPerson
Field 7: Status
kq0g1dla

kq0g1dla1#

How about using NOT IN which you can use on the WHERE clause to specify for another condition.

SELECT...
FROM..
WHERE  table_Name = 'SystemDefined' AND 
       table_schema = 'schemaAsset' AND
       COLUMN_NAME NOT IN ('Status',....) --  specify the list of names you
                                          -- don't want to show
piah890a

piah890a2#

Unless I am missing something, you can just use a WHERE clause to exclude the column(s) you do not want:

SELECT 'Field '
  + CAST(ROW_NUMBER() OVER (ORDER BY ordinal_position) AS varchar(5))+': ' 
  + COLUMN_NAME
FROM information_schema.columns 
WHERE table_Name = 'SystemDefined' 
  and table_schema = 'schemaAsset'
  and COLUMN_NAME <> 'Location'

If you have multiple columns, then you can use NOT IN ('Location', 'etc')

2vuwiymt

2vuwiymt3#

Recommend sys.columns instead of INFORMATION_SCHEMA ( here's why ).

SELECT 'Column ' 
  + CONVERT(VARCHAR(5), ROW_NUMBER() OVER (ORDER BY column_id))
  + ': ' + name
FROM sys.columns
WHERE [object_id] = OBJECT_ID(N'schemaAsset.SystemDefined')
AND name NOT IN ('Location' /* , ... other columns ... */)
ORDER BY column_id; -- because you never know how SQL Server might order

相关问题