这个动态pivot sql 在MS Studio 中完美运行,但是我无法让它在服务器上使用php 运行。我在“,”附近得到不正确的语法。并且“p”附近的语法不正确。我已经尝试了我所知道的所有类型的“执行”,以及各种标点符号。八小时就够了。请高手请教。
SQL:
declare @col varchar(8000)
declare @sql varchar(8000)
if OBJECT_ID('tempdb..#q1') is not null
drop table #q1
if OBJECT_ID('tempdb..#q2') is not null
drop table #q2
select top 5 row_number() over (
order by PTC_ASSESSMENT.ASSESSMENT_DATE desc
) as row, PTC_ASSESSMENT.ASSESSMENT_ID
into #q1
from PTC_ASSESSMENT
inner join PT_BASIC
on PTC_ASSESSMENT.PATIENT_ID = PT_BASIC.PATIENT_ID
inner join SYS_AS_DDF
on PTC_ASSESSMENT.AS_DDF_ID = SYS_AS_DDF.AS_DDF_ID
and PTC_ASSESSMENT.DISCIPLINE_CODE = SYS_AS_DDF.DISCIPLINE_CODE
where (PT_BASIC.PATIENT_CODE = '60085')
and (PTC_ASSESSMENT.DISCIPLINE_CODE = 'MD')
group by PTC_ASSESSMENT.ASSESSMENT_DATE, PTC_ASSESSMENT.ASSESSMENT_ID
select convert(varchar, ASSESSMENT_DATE, 101) as dates, QUESTION_TEXT,
case when ENTRY_TEXT is not null then ENTRY_TEXT else ANSWER_TEXT end as ANSWER_TEXT
into #q2
from VW_ASSESSMENT_DATA
inner join PT_BASIC
on VW_ASSESSMENT_DATA.PATIENT_ID = PT_BASIC.PATIENT_ID
inner join SYS_AS_DDF
on VW_ASSESSMENT_DATA.AS_DDF_ID = SYS_AS_DDF.AS_DDF_ID
inner join #q1
on VW_ASSESSMENT_DATA.ASSESSMENT_ID = #q1.ASSESSMENT_ID
where (PT_BASIC.PATIENT_CODE = '60085')
and (SYS_AS_DDF.DISCIPLINE_CODE = 'MD')
and VW_ASSESSMENT_DATA.QUESTION_ID in ( 22222, 22223, 22237, 22238, 22239, 22241, 22242 )
select @col = COALESCE(@col + ',', '') + QUOTENAME(dates)
from #q2
group by dates
set @sql = 'select QUESTION_TEXT, ' + @col + '
from (
select distinct *
from #q2
) p
pivot
(
max(ANSWER_TEXT)
for dates
in (' + @col + ' )) as pvt'
execute (@sql)
PHP:使用它来获取它。
$result = mssql_query($sql) or exit ("select query failed");
整个 PHP 脚本:
$sql = "above sql";
$result = mssql_query($sql) or exit ("select query failed");
$numrows = mssql_num_rows($result);
echo "<table width='60%' cellpadding='5%'>
<tr>";
if ($numrows > 0) {
//loop thru the field names to print the correct headers
$i = 0;
while ($i < mssql_num_fields($result))
{
echo "<th>". mssql_field_name($result, $i) . "</th>";
$i++;
}
echo "</tr>";
//display the data
while ($rows = mssql_fetch_array($result))
{
echo "<tr>";
foreach ($rows as $data)
{
echo "<td align='left'>". $data . "</td>";
}
}
}else{
echo "<tr><td colspan='" . ($i+1) . "'>No patient medical history found</td></tr>";
}
echo "</table>";