我有一份报告,显示由缩进创建的一段时间内的购买缩进。这里,@ Name参数用于过滤缩进。但是,问题是,如果@Name参数为空,则报告返回空记录。如果@Name过滤器中未选择任何内容,我想显示所有缩进的报告。以下是查询。我是SQL的新手。
SELECT INH.No_, INH.[Approved Date],
INH.Indentor, INL.No_ AS ItemCode,
INL.Description, INL.Description2,
INL.Req_Quantity, INL.[Unit of Measure],
PL.[Document No_], PH.[Order Date], PL.Quantity AS OrderedQuantity, PL.[Quantity Received]
FROM [Company$Indent Header] AS INH
INNER JOIN
[Company$Indent Line] AS INL
ON INH.No_ = INL.[Document No_]
INNER JOIN
[Company$Purchase Line] AS PL
ON INL.[Document No_] = PL.[Indent No_] AND INL.[Line No_] = PL.[Indent Line No_]
INNER JOIN
[Company$Purchase Header] AS PH
ON PL.[Document No_] = PH.No_
WHERE (INH.Indentor = @Name) AND (INL.No_ <> '') AND
(INH.[Approved Date] BETWEEN @StartDate AND @EndDate)
ORDER BY ItemCode
答案 0 :(得分:1)
您的查询是如何构建的。通过代码?因为如果@Name为空,我只会从下面的(INH.Indentor = @Name)
中省略WHERE (INH.Indentor = @Name) AND
。
我想SQL中没有条件是否要考虑WHERE
clausule中的条件,如果我错了,请纠正我。
答案 1 :(得分:1)
使用像这样的东西
WHERE (INH.Indentor = COALESCE(@Name,INH.Indentor)
并确保在参数检查后的存储过程开始时
if len(@Name) = 0
set @Name = null
这样如果@Name为空,则会将null设置为null COALESCE(@ Name,INH.Indentor)将检查@Name是否为null,然后检查现有值
答案 2 :(得分:0)
试试这个 -
SELECT
INH.No_
, INH.[Approved Date]
, INH.Indentor
, ItemCode = INL.No_
, INL.[description]
, INL.Description2
, INL.Req_Quantity
, INL.[Unit of Measure]
, PL.[Document No_]
, PH.[Order Date]
, OrderedQuantity = PL.Quantity
, PL.[Quantity Received]
FROM dbo.[Company$Indent Header] INH
JOIN dbo.[Company$Indent Line] INL ON INH.No_ = INL.[Document No_]
JOIN dbo.[Company$Purchase Line] PL ON INL.[Document No_] = PL.[Indent No_] AND INL.[Line No_] = PL.[Indent Line No_]
JOIN dbo.[Company$Purchase Header] PH ON PL.[Document No_] = PH.No_
WHERE INH.Indentor = ISNULL(@Name, INH.Indentor)
AND INL.No_ != ''
AND INH.[Approved Date] BETWEEN @StartDate AND @EndDate
ORDER BY ItemCode