MSSQL xml path()查询无法在PHP中运行

时间:2013-11-25 10:15:10

标签: php sql sql-server for-xml-path

以下查询在Microsoft SQL Server Management Studio中执行时工作正常,但是当我通过php运行查询时,我没有输出(mssql_query()之后没有任何内容被渲染)。

如果我从SQL查询中删除for xml path('')并再次在php中运行,那么现在通过mssql_query()的所有内容都会被渲染。

有没有人知道xml路径('')和PHP的任何问题,或者我是否做错了。

SELECT DISTINCT x1.AcademicYearID, x1.RefNo, x1.Source, x1.Surname, x1.FirstForename, x1.Heard,convert(VARCHAR, x1.Date, 121) as Date, Notes, School, 
(SELECT DISTINCT x2.Subject + ', ' as 'data()' from [db].[dbo].[vCC_Mkt_Enquiries] x2 WHERE x1.RefNo = x2.RefNo AND x1.Source = x2.Source for xml path('')) as Subject 
FROM [db].[dbo].[vCC_Mkt_Enquiries] x1 
WHERE x1.AcademicYearID = '13/14'

PHP

$sql = "SELECT DISTINCT x1.AcademicYearID, x1.RefNo, x1.Source, x1.Surname, x1.FirstForename, x1.Heard,convert(VARCHAR, x1.Date, 121) as Date, Notes, School, 
(SELECT DISTINCT x2.Subject + ', ' as 'data()' from [db].[dbo].[vCC_Mkt_Enquiries] x2 WHERE x1.RefNo = x2.RefNo AND x1.Source = x2.Source for xml path('')) as Subject 
FROM [db].[dbo].[vCC_Mkt_Enquiries] x1 
WHERE x1.AcademicYearID = '$year'";

$internal_events = mssql_query($sql, $connection) or die ("Error in query: $sql. ".mssql_error()); 

请注意:永远不会呈现以下或死亡错误。

or die ("Error in query: $sql. ".mssql_error()); 

1 个答案:

答案 0 :(得分:0)

您必须将返回的xml类型重新键入例如为nvarchar。就像这样:

DECLARE @XML XML

SET @XML = (

SELECT something 
FROM sometable
FOR XML PATH('items')

)

SELECT CONVERT(NVARCHAR(MAX), @XML)