@HABO给了我这个片段:
select *
from sys.dm_exec_connections as EC inner join
sys.dm_exec_sessions as ES on ES.session_id= EC.session_id
where EC.session_id = @@SPID
我想将所有字段组合到单个nvarchar中,我可以将其放入日志表
像
field1: value1 (+chr(13)+chr(10)+)
field2: value2
...
fieldn: valuen
没有手动输入所有字段名和强制转换
答案 0 :(得分:4)
您可以在查询结尾附加FOR XML PATH('')
,并将结果作为一个大型XML字符串。之后,您可以使用XML解析将其拆分。请参阅documentation on the FOR XML PATH clause和StackOverflow question that is related to parsing the output。
以下是一些生成所需输出的示例T-SQL:
declare @xmlblock xml
select @xmlblock = (
select
*
from
sys.dm_exec_connections as EC inner join
sys.dm_exec_sessions as ES on ES.session_id= EC.session_id
where
EC.session_id = @@SPID
for xml path('')
)
declare @logline nvarchar(max)
set @logline = ''
select
@logline = @logline
+ XmlChanges.value('local-name(.)', 'nvarchar(max)')
+ ': '
+ XmlChanges.value('.', 'nvarchar(max)')
+ char(13) + char(10)
from
@xmlblock.nodes('/*') as Nodes(XmlChanges)
select @logline
输出类似于:
session_id: 52
most_recent_session_id: 52
connect_time: 2013-06-12T15:05:48.607
net_transport: TCP
protocol_type: TSQL
...