培訓考試項目中,須要實現考試成績排名:排名參考項爲分數(score降序)、參加日期(attendtime升序)、第幾回參加考試(frequency升序);而且,每一個用戶只保留一條數據(pid)。php
考試結果存儲表格以下:web
指望獲得的結果爲:sql
解決思路:app
1 Create PROCEDURE [dbo].[myZhenxin] 2 @examid int 3 AS 4 BEGIN 5 if object_id('tempdb..#temp1') is not null 6 Begin 7 drop table #temp1 8 End 9 10 if object_id('tempdb..#temp2') is not null 11 Begin 12 drop table #temp2 13 End 14 15 -- Insert statements for procedure here 16 select id,frequency,attendtime, examid,score,pid into #temp1 from ExamResult where examid=@examid order by score desc,attendtime 17 18 delete #temp1 where id in(select a.id from #temp1 a, #temp1 b where a.pid = b.pid and a.score<b.score) 19 20 delete #temp1 where id in(select a.id from #temp1 a, #temp1 b where a.pid = b.pid and a.frequency>b.frequency ) 21 22 select IDENTITY(int,1,1) rankid, examid,pid,score,frequency,attendtime into #temp2 from #temp1 23 24 select * from #temp2 25 END
在sql server中,調用存儲過程的語句爲:sqlserver
exec myZhenxin '11'
在php中使用sqlsrv調用存儲過程:測試
1 if ( ($stmt = sqlsrv_query($conn, $tsql)) ) 2 { 3 // now, iterate through all the statements in 4 // stored proc or script $tsql: 5 do 6 { 7 // process the result of the iteration 8 if ( sqlsrv_num_fields($stmt) > 0 ) 9 { 10 // we have a result set 11 while ( ($row=sqlsrv_fetch_array($stmt)) ) 12 { 13 // do something with $row 14 } 15 } 16 else 17 { 18 // we have something else 19 $rowsAffected = sqlsrv_rows_affected($stmt); 20 } 21 } while ( ($next = sqlsrv_next_result($stmt)) ) ; 22 23 if ( $next === NULL ) 24 { 25 // it worked 26 } 27 else 28 { 29 // it didn't work, check sqlsrv_errors() 30 } 31 32 sqlsrv_free_stmt($stmt); 33 }