2015-12-01 79 views
0

每天在第一次運行sql作業時,我需要更新一些列。我的工作將從每天凌晨4點開始。確定作業今天是否第一次運行

,所以我可以做到這一點:

IF(CONVERT(VARCHAR(8),GETDATE(),108) = '04:00:00') 
BEGIN 
// Update 
END 

但是,如果由於某種原因,我的工作不能在凌晨4點運行。我怎樣才能重置這些列。任何想法,建議,幫助。

我要求如下: 我的系統得到任務從我的最終用戶。這項工作需要根據員工的能力將這些任務分配給員工。所以,我有一張EmpId,MaxAssignments表(最多可在一天內分配的任務數)& AssignmentsCount(已分配任務數)列。在1日運行每天我要設置這個「AssignmentsCount」值設置爲0

+2

也許在一天只運行一次的單獨作業中進行更新? – GolezTrol

+0

爲什麼你選擇4am而不是00.01 am?如果時間表在凌晨3點移動,應該發生什麼?應該修改sql代碼以匹配嗎?請解釋您的要求,而不是您正在嘗試使用的解決方案... – Paolo

+0

@Paolo我將我的要求添加到了 –

回答

0

您應該能夠使用類似的代碼是什麼如下所示的作業步驟內。這些SQL語句被解釋爲解釋的評論。爲了簡潔起見,您可以將它們結合起來,甚至可以將它們變成一個單獨的標量函數,該函數需要一個作業標識符,並在第一次運行時返回true或false。

DECLARE @job_id uniqueidentifier 
DECLARE @run_requested_date DATETIME 
DECLARE @first_run_today DATETIME 

-- Use Tokens in Job Steps 
-- https://msdn.microsoft.com/en-us/library/ms175575.aspx 
-- Within your SQL Agent job step you can use this tokenized 
-- statement to get the job_id. 
--SET @job_id = CONVERT(uniqueidentifier, $(ESCAPE_NONE(JOBID))) 

-- You can use this statement instead, but it will break if the 
-- job name is changed and you forget to update the [name] 
-- parameter below ('Test' is the job name in this example) 
SELECT @job_id = job_id 
    FROM msdb.dbo.sysjobs 
WHERE name = 'Test' 

-- Debug statement 
PRINT 'job_id = ' + CONVERT(VARCHAR(255), @job_id) 

-- Get the scheduled run time for this currently 
-- executing job (can alternatively use the 
-- start_execution_date column instead) 
SELECT @run_requested_date = run_requested_date 
    FROM msdb.dbo.sysjobactivity 
WHERE job_id = @job_id 

-- Debug statement 
PRINT 'run_requested_date = ' + CONVERT(VARCHAR(50), @run_requested_date, 126) 

-- For the given job, find any job history row that 
-- was successfully execute at an earlier time on 
-- this date. 
-- 
-- The msdb.dbo.agent_datetime() function is a built-in 
-- function that will values from the separate date and time 
-- columns in the job history table and convert them to a 
-- single datetime value. 
SELECT @first_run_today = msdb.dbo.agent_datetime(run_date, run_time) 
    FROM msdb.dbo.sysjobhistory 
WHERE JOB_ID = @job_id 
    AND run_status = 1 -- Successful 
    AND run_date = CONVERT(VARCHAR(10), @run_requested_date, 112) -- YYYYMMDD format compare 
    AND msdb.dbo.agent_datetime(run_date, run_time) < @run_requested_date 

-- Debug statement 
PRINT 'first_run_today = ' + CONVERT(VARCHAR(50), @first_run_today, 126) 

-- If the first_run_today variable is null then 
-- that means for the current date we did not 
-- any successful runs of this job before now. 
IF @first_run_today IS NULL 
BEGIN 
    PRINT 'This *is* the first run.' 
    -- First run statements go here. 
END 
ELSE 
BEGIN 
    PRINT 'This is *not* the first run.' 
    -- Non first run statements go here. 
END