2016-09-23 47 views
1

我試圖用Stored Procedure創建一個查詢。我能夠創建它,並且當我運行它時沒有問題。這裏是我的StoredProcedure帶臨時表的Codeigniter SQL

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER PROCEDURE SP_Penilaian 
    @Nip varchar(50) 
AS 
BEGIN 

    select * INTO #tMP from historyposition where nip = ''[email protected]+'' order by approveddate desc 

declare @NewPosition varchar(50), @NewPositionLast varchar(50), @ApproveDate datetime, @ApproveDateLast datetime 
select top 1 @NewPositionLast = NewPosition, @ApproveDateLast=ApprovedDate from #tmp 
WHILE EXISTS (SELECT * FROM #tMP) 
BEGIN 
    select top 1 @NewPosition = NewPosition, @ApproveDate=ApprovedDate from #tmp 
    if (@NewPosition = @NewPositionLast) 
    begin 
     set @NewPositionLast = @NewPosition 
     set @ApproveDateLast = @ApproveDate 
    end 
    else 
    begin 
     break 
    end 
    delete top(1) #tMP 
END 
select @NewPositionLast 'LatesUpgradePosition' , @ApproveDateLast 'LatesUpgradeDate' 
END 
GO 

這個我怎麼運行它

sp_penilaian '1500060' 

這裏是resullt

enter image description here

確定。問題是當我試圖在Codeigniter中調用我的SP時。

$nip = '1500060'; 
$filt_outlet = $this->db->query("SP_Penilaian '".$nip."'")->row(); 

,然後我試圖檢查我的數據與此

echo "<pre>".print_r($filt_outlet)."</pre>"; 

,但我得到空的數據。那麼如何在CodeIgniter中使用臨時表?或者如果我不能使用臨時表,我可以創建表並將其放入我的存儲過程中?

對不起,我的英語不好。

+0

爲什麼所有的複雜性添加SET NOCOUNT ON;存儲過程?你只需要最近更新的位置和日期/時間 - 只需要查詢即可。沒有臨時表需要,沒有動態SQL需要。 #avoid-the-rbar –

+0

好吧,我只是好奇爲什麼每個包含'#'表的SP都不起作用。我沒有使用這個SP。我只是在我的PHP中寫入一個查詢。 – YVS1102

回答

3

嘗試後BEGIN

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER PROCEDURE SP_Penilaian 
    @Nip varchar(50) 
AS 
BEGIN 

SET NOCOUNT ON; /*<--Add here*/ 

    select * INTO #tMP from historyposition where nip = ''[email protected]+'' order by approveddate desc 

declare @NewPosition varchar(50), @NewPositionLast varchar(50), @ApproveDate datetime, @ApproveDateLast datetime 
select top 1 @NewPositionLast = NewPosition, @ApproveDateLast=ApprovedDate from #tmp 
WHILE EXISTS (SELECT * FROM #tMP) 
BEGIN 
    select top 1 @NewPosition = NewPosition, @ApproveDate=ApprovedDate from #tmp 
    if (@NewPosition = @NewPositionLast) 
    begin 
     set @NewPositionLast = @NewPosition 
     set @ApproveDateLast = @ApproveDate 
    end 
    else 
    begin 
     break 
    end 
    delete top(1) #tMP 
END 
select @NewPositionLast 'LatesUpgradePosition' , @ApproveDateLast 'LatesUpgradeDate' 
END 
GO 
+0

它解決了我的問題。但爲什麼我需要'SET NOCOUNT ON;'? – YVS1102

+0

我從這裏學到了[鏈接] http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/ –

0

看起來問題不在於實際的存儲過程,而在於你調用它的方式。嘗試:

$nip = '1500060'; 
$sp = "CALL SP_Penilaian(?)"; 

而到了夾傳遞給存儲過程,你可以用CodeIgniter的數據庫查詢funtion像這樣:

$filt_outlet = $this->db->query($sp, array('nip'=>$nip));