2011-05-26 102 views
0

我的存儲過程有點麻煩。 我寫了一個存儲過程,我在使用遊標。 每件事情都很好,直到我將光標處的值插入臨時表的地方。 這裏是錯誤mssql光標的小問題,在光標內的臨時表中插入

消息156,級別15,狀態1,過程ors_DailyReportMessageStatus,行中的關鍵字 '其中' 36 附近有語法錯誤。

這裏是代碼

ALTER PROCEDURE [dbo].[ors_DailyReportMessageStatus] 
-- Add the parameters for the stored procedure here 
@startDate datetime, @endDate datetime 
AS 
BEGIN 
-- SET NOCOUNT ON added to prevent extra result sets from 
-- interfering with SELECT statements. 
DECLARE @num int; 
DECLARE @stat varchar(20); 
DECLARE @statusCursor CURSOR 
SET @statusCursor = CURSOR FOR 
select count(ms.status) as message, ms.status from message_status ms JOIN [message] m on m.id=ms.message_id 
where (m.ADDED_ON >= @startDate AND m.ADDED_ON < @endDate) GROUP BY ms.status 

SET NOCOUNT ON; 
if object_id('tempdb..#tempdailystatus') is not null 
begin 
    drop table #tempdailystatus 
end 

CREATE TABLE #tempdailystatus(id int identity, total int , [status] varchar(20)); 
insert into #tempdailystatus ([status]) 
select distinct([status]) from message_status; 


open @statusCursor 
fetch next from @statusCursor into @num, @stat; 
while @@FETCH_STATUS = 0 

    begin 
    -- this is where the error is 
    insert into #tempdailystatus (total) values (@num) where id = (select id from #tempdailystatus where [status] = @stat) 
    -- this were just to see whether the cursor is ok. and it is 
    --print @stat 
    --print @num ; 
    fetch next from @statusCursor into @num,@stat 
end 

close @statusCursor 
deallocate @statusCursor 


-- Insert statements for procedure here 
-- SELECT * from #tempdailystatus 
drop table #tempdailystatus 
END 

很可能我忽略的東西嗎?似乎我忘記了一些東西。

感謝你讀這篇文章,給了建議.will欣賞吧^ _^

+0

您不能在INSERT語句中擁有WHERE子句,除非它是SELECT子句的一部分。你到底在做什麼? – 2011-05-26 16:49:23

回答

1

嘗試更換:

insert into #tempdailystatus (total) values (@num) where id = (select id from #tempdailystatus where [status] = @stat) 

有:

If Exists(Select 1 From #tempdailystatus where [status] = @stat) 
    Begin 
    insert into #tempdailystatus (total) Values(@num) 
    End 

我對你們的邏輯一些假設,所以你可能需要做相應的調整。