Reputation: 883
In my application I need to call a Stored Proc Asynchronously. For this I am using Sql Service Broker. These are the steps Involved in creating the asynchronous calling.
1) I created Message,Contract,Queue,Service. And Sending messages.I can see my messages in 'ReceiveQueue1'.
2) I created a stored Proc and a Queue When I execute the Stored Proc(proc_AddRecord) its executing only once. Its reading all the records in the Queues and adding those records to the table. Upto this point its working fine. But when I add some new messages to 'ReceiveQueue1' my stored proc is not adding those records automatically to the table. I have to re execute the Stored Proc(proc_AddRecord) inorder to add the new messages. Why is the Stored proc is not getting executed. What I am supposed to do in order to call the Stored Proc Asynchronously. The whole point of using Service Broker is to call stored procs asynchronously. I am totally new to SQL Server Service Broker. Appreciate any help. Here is my code for the stored Proc
#--exec proc_AddRecord
ALTER PROCEDURE proc_AddRecord
AS
Declare
@Conversation UniqueIdentifier,
@msgTypeName nvarchar(200),
@msg varbinary(max)
While (1=1)
Begin
Begin Transaction;
WAITFOR
(
Receive Top (1)
@Conversation = conversation_handle,
@msgTypeName = message_type_name,
@msg = message_body
from dbo.ReceiveQueue1
), TIMEOUT 5000
IF @@Rowcount = 0
Begin
Rollback Transaction
Break
End
PRINT @msg
If @msg = 'Sales'
BEGIN
insert into TableCity(deptNo,Manager,Group,EmpCount) VALUES(101,'Reeves',51, 29)
COMMIT Transaction
Continue
End
If @msg = 'HR'
BEGIN
insert into TableCity(deptNo,Manager,Group,EmpCount) VALUES(102,'Cussac',55, 14)
COMMIT Transaction
Continue
End
Begin
Print 'Process end of dialog messages here.'
End Conversation @Conversation
Commit Transaction
Continue
End
Rollback Transaction
END
ALTER QUEUE AddRecorQueue
WITH ACTIVATION (
PROCEDURE_NAME=proc_AddRecord,
MAX_QUEUE_READERS = 1,
STATUS = ON,
EXECUTE AS 'dbo');
Upvotes: 1
Views: 3390
Reputation: 7314
You say you are executing the stored procedure, you shouldn't need to do that, not even once, it should always be done with the activation.
Should your activation be on your 'ReceiveQueue1' instead of your 'AddRecorQueue' I can't see the rest of your code, but the names suggest it.
Where does your stored procedure begin and end? Generally I'd put BEGIN just after the AS statement and END where the stored procedure should end, If you don't have these then you'd need a GO statement to separate it off. Otherwise your ALTER QUEUE statement would be part of the stored procedure
You also have "Rollback Transaction" so even if the activation was working it would all get rolled back, or raise an error saying there was no transaction had one of the IF statements been triggered.
I suggest you follow this tutorial for service broker in general and this one about internal activation. They should get you started.
Upvotes: 3