SQL Server 2008结果字符串替换 - 多标识符

时间:2017-03-29 06:50:02

标签: sql string sql-server-2008 replace for-xml

我目前无法运行以下SQL查询:

SELECT 
    c.[DeviceName],
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'CFRM-Server%' FOR XML PATH('')),1,3,'') AS 'CFRM',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Communication Module%' FOR XML PATH('')),1,3,'') AS 'Communication Module',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'GEBIT-Commons-Java%' FOR XML PATH('')),1,3,'') AS 'Gebit Commons Java',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'GEBIT-Commons_JBOSS%' FOR XML PATH('')),1,3,'') AS 'Gebit Commons JBOSS',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Mobile Store%' FOR XML PATH('')),1,3,'') AS 'Mobile Store',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'NEWPOSS-Store-Server%' FOR XML PATH('')),1,3,'') AS 'NEWPOSS',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Store Portal - Complete%' FOR XML PATH('')),1,3,'') AS 'Store Portal',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Store S&R Services%' FOR XML PATH('')),1,3,'') AS 'SSR'
FROM 
    [dbo].[Computer] as c WITH (NOLOCK)
WHERE
    c.[DeviceName] LIKE '%STL01'
ORDER BY 
    c.[DeviceName] ASC;

输出很好,但似乎数据库中的一个产品(' SSR')有一个"&"导致输出损坏的字符('存储S& R服务'而不是' S& R服务xx.xx.xx')。

是否有机会在输出中执行字符串替换?

'对于XML'是因为数据库中每个DeviceName有两个条目,导致结果为空。

感谢任何帮助:)

1 个答案:

答案 0 :(得分:0)

看看这个:

DECLARE @teststring VARCHAR(100)='This is for test & show';

SELECT(SELECT ' + ' + @teststring FOR XML PATH(''));

SELECT((SELECT ' + ' + @teststring FOR XML PATH(''),TYPE).value('.','nvarchar(max)'));

两个结果是:

+ This is for test & show
+ This is for test & show

FOR XML与禁用字符一起使用(在大多数情况下,'<,>和&')将导致转义实体。 XML只是不能使用这些字符,因为它们具有元语义。

还有更多字符会导致像换行符或许多外来字符等麻烦......

简单的解决方案:如第二行所示换行SELECT ... FOR XML ...,并通过value()方法读取内部值。这将隐式地将实体重新编码为前一个字符。