我创建了一个服务代理,它将id存储在队列表中。但问题是,当我想在存储过程中获取id时,它现在被格式化为xml。因为服务代理消息是XML。
我怎样才能每次都获得最后一次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 :(得分: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行。只需考虑一下。