0
如何在設置變量時使用if exists
子句?如果在SQL中設置變量時存在的問題
我有這樣的設置,使頂select語句的結果(@F1Runs, @F2Runs, @F3Runs
,所有相應的Date
)插入到臨時表#WeekEnding
,然後從那裏進入實際的表。
問題是,在某些日期,某些或所有熔爐沒有「運行次數」結果。因此,當我設置變量@ F1Runs,@ F2Runs和@ F3Runs時,我試圖找到一種方法來放置一個IF EXISTS語句或類似的東西,以便當它們不存在時以0的形式插入表中。
我得到的錯誤是:
無法將NULL值插入列 'F2Runs',表 'WWALMDB.dbo.WeeklyRuns';列不允許有空值。 INSERT失敗。
我的代碼:
Select
jr.FurnaceID, Count(Distinct jr.JobID) As 'Number of Runs'
Into
#WeekEnding
From
dbo.JobReports jr
Where
jr.StartDateTime >= @StartDate
and jr.EndDateTime < @Enddate
Group By
jr.FurnaceID
Order By
Count(jr.JobID) DESC
Select @F1Runs = [Number of Runs]
From #WeekEnding
Where FurnaceID = 1
Select @F2Runs = [Number of Runs]
From #WeekEnding
Where FurnaceID = 2
Select @F3Runs = [Number of Runs]
From #WeekEnding
Where FurnaceID = 3
If Exists (Select wr.WeekEnding
From WWALMDB.dbo.WeeklyRuns wr
Where wr.WeekEnding = DATEADD(day, -1, @Enddate))
Begin
Update WWALMDB.dbo.WeeklyRuns
Set F1Runs = @F1Runs,
F2Runs = @F2Runs,
F3Runs = @F3Runs
Where WeeklyRuns.WeekEnding = DATEADD(day, -1, @Enddate)
End
Else
Begin
Insert Into WWALMDB.dbo.WeeklyRuns (WeekEnding, F1Runs, F2Runs, F3Runs)
Values (DATEADD(day, -1, @Enddate), @F1Runs, @F2Runs, @F3Runs)
End
不知道爲什麼,但第一個選項提出了一些錯誤。第二個工程,但。謝謝! – MadelineK