如何在SQL Server中选择特定的列名称

时间:2013-02-27 01:08:45

标签: sql sql-server select columnname

这是我之前关于如何在SQL Server中迭代字符串的问题:

现在我该如何专门选择列名? 这是我选择列的代码:

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'

这是输出:

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

这是我在选择特定列名时所需的输出:

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

3 个答案:

答案 0 :(得分:3)

如何使用NOT IN可以在WHERE子句中使用{1}}来指定其他条件。

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

答案 1 :(得分:1)

除非我遗漏了某些内容,否则您只需使用WHERE子句排除您不想要的列:

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'

如果您有多列,则可以使用NOT IN ('Location', 'etc')

答案 2 :(得分:0)

推荐sys.columns而不是INFORMATION_SCHEMAhere'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