如何从表中检索列名并解析sql 2012中每个字段名的结果

时间:2013-06-20 16:55:49

标签: sql-server-2012

如何检索我正在执行选择的表的列名?我正在尝试将结果附加到每个字段名称的先前结果。

示例(不起作用):

declare @result as nvarchar(max)
concat(select distinct parse(@result, COLName(field1), N':' from sometable, field1))

sometable:

id,unit
`---------`
1,quart
2,gallon
3,liter

结果

id:1,2,3 单位:夸脱,加仑,升

我实际上是尝试在我的表中包含text,varchar,char的每个字段上使用以下select语句执行此操作,其中size大小小于4000:

我正在尝试解析的表的实际字段列表(这有效):

select top 1000 SCHEMA_NAME([o].schema_id) as [Schema Name],
       [s].name as [Table Name],
       [c].name as [Field Name],
       [t].name as [Type],
       [c].max_length as [Length],
       [c].precision,
       [c].scale,
       [c].is_identity
from sys.sysobjects as [s]
inner join sys.all_columns as [c] on [s].id = [c].object_id
inner join sys.systypes as [t] on [c].system_type_id = [t].xtype 
inner join sys.objects as [o] on [s].id = [o].object_id
where [s].xtype like 'U' and [t].name not like 'sysname%' and [s].name=N'TableName'

这样我就能清楚地看到每个具有不同结果集的字段的名称。

1 个答案:

答案 0 :(得分:1)

如果您事先了解文件列表,则可以使用以下内容:

SELECT
(
    SELECT cast(id as varchar(50)) + ','
    FROM sometable
    ORDER by id
    FOR XML PATH('')
) as list1

UNION ALL

SELECT
(
    SELECT unit + ','
    FROM sometable
    ORDER by id
    FOR XML PATH('')
) as list2

...