我的存储过程遇到了一些麻烦。 我写了一个存储过程,我正在使用游标。 一切正常,直到我从光标到临时表插入值的地方。 这是错误
Msg 156,Level 15,State 1,Procedure ors_DailyReportMessageStatus,Line 36 关键字'where'附近的语法不正确。
这是代码
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
我可能会忽视某些事情吗?好像我忘记了什么。
感谢您阅读此内容并提供建议。请欣赏它^ _ ^
答案 0 :(得分: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
我对你的逻辑做了一些假设,所以你可能需要相应调整。