我需要将单行的所有值(而不是空值)放入一个字符串中,例如
表:
CustomerName Address Zip
Alex Moscow 1234
结果:
CustomerName: Alex
Address: Moscow
Zip: 1234
重要说明 - 我不知道字段名称/类型,因此它应该遍历所有字段,并且所有非空值都添加到列表中。
看起来它可以使用xquery执行此操作,但无法找到正确的语法。 任何提示?
谢谢!
答案 0 :(得分: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)
答案 1 :(得分:1)
select 'CustomerName: ' + isNull(CustometName, '') + 'Address: '
+ isNull(Address, ''), + 'Zip:' + isNull(Zip, '') from [TableName]
也许您需要将一些值转换为varchar
答案 2 :(得分: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)