2

这是我之前关于如何在 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
4

3 回答 3

3

如何使用NOT IN可以在WHERE子句上使用的来指定另一个条件。

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
于 2013-02-27T01:13:33.343 回答
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')

于 2013-02-27T01:14:16.477 回答
0

推荐sys.columns而不是INFORMATION_SCHEMA这就是为什么)。

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
于 2013-02-27T03:05:03.430 回答