在SQL表中,我将列作为Start_Date,End_Date和IsActive。
在每个插入中,Start_Date将有一个有效的日期时间条目,End_Date将为Null,IsActive将为0。
30分钟后,我需要用当前日期时间更新End_Date,为IsActive更新1。这是在SQL Express中。我不能使用作业调度程序。我不想使用Windows任务计划程序。
触发器具有插入或更新后的限制。有办法解决这个问题吗?
答案 0 :(得分:1)
以下示例使用服务代理激活的存储过程和会话计时器定期更新表。收到DialTimer消息后,激活的dbo.UpdateSqlTableOnTimer proc会更新表并启动新计时器。 dbo.StartUpdateSqlTableOnTimer proc启动初始计时器并返回会话句柄。如果需要,指定dbo.StopUpdateSqlTableOnTimer的句柄以停止计时器循环。
请注意,数据库必须启用服务代理。如果尚未启用,请使用ALTER DATABASE
启用服务代理:
ALTER DATABASE YourDatabase
SET ENABLE_BROKER;
USE YourDatabase;
GO
CREATE PROC dbo.StartUpdateSqlTableOnTimer
--begin initial conversation and timer
AS
DECLARE @ConversationHandle uniqueidentifier;
BEGIN DIALOG CONVERSATION @ConversationHandle
FROM SERVICE UpdateSqlTableOnTimer
TO SERVICE 'UpdateSqlTableOnTimer', 'CURRENT DATABASE'
ON CONTRACT [DEFAULT]
WITH ENCRYPTION = OFF;
BEGIN CONVERSATION TIMER (@ConversationHandle)
TIMEOUT = 1800;
SELECT @ConversationHandle AS ConversationHandle;
GO
CREATE PROC dbo.StopUpdateSqlTableOnTimer
@ConversationHandle uniqueidentifier
--end conversation
AS
END CONVERSATION @ConversationHandle;
GO
CREATE PROC dbo.UpdateSqlTableOnTimer
AS
SET XACT_ABORT ON;
SET NOCOUNT ON;
DECLARE
@ConversationHandle uniqueidentifier
, @MessageTypeName sysname
, @EventNotificationDetails xml
, @EventLogMessage nvarchar(MAX);
BEGIN TRY
BEGIN TRAN;
RECEIVE TOP(1)
@ConversationHandle = conversation_handle
, @MessageTypeName = message_type_name
, @EventNotificationDetails = CAST(message_body AS xml)
FROM dbo.QueueForUpdateSqlTableOnTimer;
IF @@ROWCOUNT > 0
BEGIN
IF @MessageTypeName = N'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer'
BEGIN
--update IsActive and End_Date here
--start new timer
BEGIN CONVERSATION TIMER (@ConversationHandle)
TIMEOUT = 1800;
END
ELSE
BEGIN
IF @MessageTypeName = N'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'
BEGIN
END CONVERSATION @ConversationHandle;
END
ELSE
BEGIN
END CONVERSATION @ConversationHandle WITH ERROR = 1 DESCRIPTION = 'Unexpected message type received';
END;
END;
END;
COMMIT;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
GO
--create queue with proc activation
CREATE QUEUE dbo.QueueForUpdateSqlTableOnTimer
WITH STATUS=ON,
ACTIVATION (
PROCEDURE_NAME = dbo.UpdateSqlTableOnTimer,
MAX_QUEUE_READERS = 1,
EXECUTE AS OWNER ) ;
GO
CREATE SERVICE UpdateSqlTableOnTimer
ON QUEUE dbo.QueueForUpdateSqlTableOnTimer
([DEFAULT]);
GO
EXEC dbo.StartUpdateSqlTableOnTimer;
GO
EXEC dbo.StopUpdateSqlTableOnTimer @ConversationHandle = '<specify value from dbo.StartUpdateSqlTableOnTimer>';
GO