2011-08-22 43 views
3

我需要把所有的,不为​​空,单列的值转换成一个字符串,如TSQL:行中的所有字段的值成一个字符串

表:

CustomerName Address Zip 
Alex   Moscow 1234 

导致:

CustomerName: Alex 
Address: Moscow 
Zip: 1234 

重要说明 - 我不知道字段名称/类型,所以它应该经过所有字段并且所有非空值都会添加到列表中。

看起来它可以使用xquery完成此操作,但无法找到正确的语法。 任何提示?

谢谢!

回答

4
select T2.N.value('local-name(.)', 'nvarchar(128)')+': '+ 
     T2.N.value('.', 'nvarchar(max)') 
from (select * 
     from YourTable 
     for xml path(''), type) as T1(X) 
    cross apply T1.X.nodes('/*') as T2(N) 
+0

+1真不错的Mikael –

+0

谢谢,酷,看起来像我正在寻找的,将尝试实现这一点。 –

+0

嗨Mikael,如果我有你的表中的所有字段FieldName和FieldDescription的表 - 我如何修改此语句显示FieldDescription而不是字段名称?谢谢! –

1
select 'CustomerName: ' + isNull(CustometName, '') + 'Address: ' 
+ isNull(Address, ''), + 'Zip:' + isNull(Zip, '') from [TableName] 

也许你需要投一些价值为varchar

+0

对不起,请参阅重要说明,加入最近 –

1

不一样优雅的的Mikael的解决方案。但我仍然想包括它。

DECLARE @yourtable nvarchar(128) 
DECLARE @sql as nvarchar(2100) 
DECLARE @col as nvarchar(2000) 

SET @yourtable = '<tablename>' 

SELECT @col = coalesce(@col, '') + '+'''+t2.column_name+': '' + cast([' + t2.column_name + '] as varchar) + char(32)' 
FROM INFORMATION_SCHEMA.TABLES t1 join 
INFORMATION_SCHEMA.COLUMNS t2 on t1.table_name = t2.table_name 
where t2.is_nullable = 'NO' and t1.table_name = @yourtable 
and t1.table_type = 'BASE TABLE' and t1.table_schema = t2.table_schema 
and t2.table_schema = 'dbo' 
SET @sql = 'select ' + stuff(@col, 1,1,'') +' from ' + @yourtable 
EXEC (@sql) 
+0

对不起,请参阅重要笔记,最近添加 –

+0

谢谢,我也写过类似的代码,但后来想,如果我可以这样做的Mikael的解决方案 –

相关问题