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