![](/img/trans.png)
[英]My Microsoft Access Append Query (VBA and SQL) works for a literal, but not for a variable
[英]SQL query works with variable but not with literal
我在SQL Server中有一個用戶定義的表值函數,名稱為dbo.GetBillsByDate
,它接受一個日期參數@dateOf
。
該函數將成功返回2015年10月除2015年10月14日以外的所有日期。特殊日期會導致除以零錯誤,並返回警告。 這是確切的文本:
Divide by zero error encountered.
Warning: Null value is eliminated by an aggregate or other SET operation.
該函數在14號以外的每個日期運行都會使我感到困惑,但是我發現當我使用變量傳遞數據時,該函數將成功返回。 這引起更多的混亂。
所以:
select * from GetBillsByDate('10/14/2015');
返回錯誤,並且:
declare @dateOf date;
set @dateOf = '10/14/2015';
select * from GetBillsByDate(@dateOf);
才不是。
有見識嗎?
編輯: dbo.GetBillsByDate
create function [dbo].[GetBillsByDate](@dateOf date)
returns table as
return
select propertyID PropertyCode,
billDate DateOf,
accountNum AccountNumber,
address1 Address1,
address2 Address2,
dateadd(day, 1-day(@dateOf), @dateOf) DatePosted,
glcode LedgerCode,
currMonthPostTotal AmountPosted
from AccruedBills
where convert(date, dateCreated) = @dateOf
and
startDate < endDate
and
billTotal >= 0
and
currMonthPostTotal<>0
union
select propertyID,
billDate,
accountNum,
address1,
address2,
dateadd(day, 1, dateadd(month, -1, dateadd(day, 1-day(@dateOf), @dateOf))),
glcode,
prevMonthPostTotal
from AccruedBills
where convert(date, dateCreated) = @dateOf
and
prevMonthPostTotal<>0
and
startDate < endDate
and
billTotal >= 0
union
select propertyID,
billDate,
accountNum,
address1,
address2,
dateadd(day, 1, dateadd(month, -1, dateadd(day, 1, dateadd(month, -1, dateadd(day, 1-day(@dateOf), @dateOf))))),
glcode,
remaMonthPostTotal
from AccruedBills
where convert(date, dateCreated) = @dateOf
and
remaMonthPostTotal<>0
and
startDate < endDate
and
billTotal >= 0
AccruedBills是一個視圖。 查詢:
select * from AccruedBills where convert(date, dateCreated) = '20151014'
成功返回。
在AccruedBills
視圖中發現問題。 該視圖使用在每個先前CTE上構建的順序CTE。 其中兩個查詢包含除法運算。 但是,在達到這些表達式之前,我將濾除divisor列中包含的0。 似乎@AdamMartin所說的是原因。 每次評估時,視圖均未按照指定的順序進行評估。 通過顯式檢查除以0的除法,查詢成功完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.