2011-05-26 33 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 

我对你们的逻辑一些假设,所以你可能需要做相应的调整。