2015-06-16 75 views
0

我已經創建了一個將ID存儲在隊列表中的服務代理。但問題是,當我想在存儲過程中獲取id時,它現在格式化爲xml。因爲服務代理消息是XML。SQL Service Broker

我怎樣才能每次獲得最後一個ID,因爲在更新一行之後觸發器被觸發。

下面我的代碼=>

/****** Object: Trigger [dba].[TriggerCall] Script Date: 6/16/2015 2:55:57 PM ******/ 

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER TRIGGER [dba].[TriggerCall] ON [dba].[CallID] FOR  UPDATE 
AS 

BEGIN 
    SET NOCOUNT ON; 
    DECLARE @MessageBody XML 
    DECLARE @ID varchar(50) 
    -- Insert statements for trigger here 

       --get relevant information from inserted/deleted and convert to xml message 
     SET @MessageBody = (SELECT Id FROM inserted 
     FOR XML AUTO)   

        If (@MessageBody IS NOT NULL) 
     BEGIN 

        DECLARE @Handle UNIQUEIDENTIFIER; 
        BEGIN DIALOG CONVERSATION @Handle 
        FROM SERVICE [TestServiceInitiator] 
        TO SERVICE 'TestServiceTarget' 
        ON CONTRACT [TestContract] 
        WITH ENCRYPTION = OFF; 
        SEND ON CONVERSATION @Handle 
        MESSAGE TYPE [TestMessage](@MessageBody); 
     END 

END 



/****** Object: StoredProcedure [dbo].[usp_GetCall] Script Date: 6/16/2015 2:44:27 PM ******/ 

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER PROCEDURE [dbo].[usp_GetCall] 
AS 
BEGIN 
DECLARE @message_type varchar(100) 
DECLARE @dialog uniqueidentifier, @message_body XML; 
Declare @Object as Int; 
Declare @URL as varchar(255) 
Declare @ResponseText as Varchar(8000); 
Declare @ID as Varchar(38); 

WHILE (1 = 1) 
     BEGIN -- Receive the next available message from the queue 
     WAITFOR ( 
        RECEIVE TOP(1) @message_type = message_type_name,  
        @message_body = CAST(message_body AS XML),  
        @dialog = conversation_handle 

     FROM dbo.TestQueue), TIMEOUT 500 if (@@ROWCOUNT = 0 OR @message_body IS NULL) 

     BEGIN 

        BREAK 
     END 
       ELSE 
        BEGIN 

INSERT INTO [dbo].[testtabel] 
     ([id] 
     ,[callid], 
     [test]) 
VALUES 
     ('111', '111', @message_body) 


        END 
     END CONVERSATION @dialog 
     END 
END 

回答

0

如果我正確理解你的問題,你只是看向ID補充水分成一個int。如果是這種情況,應該做以下事情:

use tempdb; 
create table inserted (id int); 
insert into inserted values (1); 
declare @message_body xml; 

set @message_body= (select * from inserted for xml auto); 
select @message_body.value('(/inserted/@id)[1]', 'int'); 

魔法是最後一行(其餘的只是設置爲我測試)。

雖然,我會藉此機會澄清你似乎有的錯誤觀念。 SQL服務器中的觸發器不是每行都觸發,而是每批觸發。因此,如果您針對表執行更新並更新50行,觸發器將被觸發一次,插入(和刪除)的表將包含50行。只是要考慮到一些事情。