【问题标题】:SQL Server 2008 result String replacement - multi-identifierSQL Server 2008 结果字符串替换 - 多标识符
【发布时间】:2017-08-22 12:22:59
【问题描述】:

我目前无法运行以下 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”)有一个“&”字符,导致输出损坏(“Store S&R Services”而不是“S&R Services xx.xx.xx ')。

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

“For XML”的原因是因为数据库中每个 DeviceName 的双重条目导致结果为空。

任何帮助表示赞赏:)

【问题讨论】:

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


    【解决方案1】:

    看看这个:

    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()方法读取内部值。这将隐式地将实体重新编码为以前的字符。

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 2010-11-11
      • 2015-10-13
      • 1970-01-01
      相关资源
      最近更新 更多