为什么我不能在 select 语句中使用 if 语句?有人知道另一种方法吗?
Select b.ItemKey, a.CatKey, a.ParentKey, a.CatName, g.ItemID, c.UserFld1, c.UserFld3, c.UserFld5, f.UOMID, e.SizeValue
From dbo.timWebCategory a Inner JOIN
dbo.timWebCategoryItem b ON a.CatKey = b.CatKey Inner JOIN
mas500_app.dbo.timItem c ON b.ItemKey = c.ItemKey Inner JOIN
dbo.cpsIMItemDetails d ON c.ItemKey = d.ItemKey Inner JOIN
dbo.timItemSize e ON c.ItemKey = e.ItemKey Left JOIN
dbo.timVolumeUOM f ON e.VolUOMKey = f.VolUOMKey Left JOIN
mas500_app.dbo.vWebItem g ON c.ItemKey = g.ItemKey
Where a.Catkey = @Key
AND d.IntFlg = 1
If @color is not Null
Begin
AND c.UserFld1 = @color
End
Order By f.UOMID, e.SizeValue**
返回这个: 关键字“AND”附近的语法不正确。
Select b.ItemKey, a.CatKey, a.ParentKey, a.CatName, g.ItemID, c.UserFld1, c.UserFld3, c.UserFld5, f.UOMID, e.SizeValue
From dbo.timWebCategory a Inner JOIN
dbo.timWebCategoryItem b ON a.CatKey = b.CatKey Inner JOIN
mas500_app.dbo.timItem c ON b.ItemKey = c.ItemKey Inner JOIN
dbo.cpsIMItemDetails d ON c.ItemKey = d.ItemKey Inner JOIN
dbo.timItemSize e ON c.ItemKey = e.ItemKey Left JOIN
dbo.timVolumeUOM f ON e.VolUOMKey = f.VolUOMKey Left JOIN
mas500_app.dbo.vWebItem g ON c.ItemKey = g.ItemKey
Where a.Catkey = @Key
AND d.IntFlg = 1
If @color is not Null
Begin
AND c.UserFld1 = @color
End
Order By f.UOMID, e.SizeValue**
Returns this:
Incorrect syntax near the keyword 'AND'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试一下...
Try that...
把它“翻过来”。您不能有条件地插入 AND,您必须始终说出 AND,然后您可以使用 if-else(或只是一个 OR,如其他答案)有条件地提供您想要的条件或只是 true/false。
Turn that "inside out". You can't conditionally insert the AND, you have to always say the AND, and you may then use if-else (or just an OR, like the other answer) to conditionally provide either the condition you want or just true/false.
您可以使用
if
语句来控制执行哪些语句,但不能使用它来删除部分查询。不以这种方式构建的原因之一是查询的执行计划会根据输入的不同而不同,因此每次都必须创建一个新的执行计划并且无法重复使用。
有不同的方法可以处理这个问题,例如,如果变量为 null,则使用 isnull 函数将值与其自身进行比较:
或者在比较之前检查是否为 null:
您始终可以将
if
放入code> 查询周围的语句,这将为您提供两个版本的查询,每个版本都有一个比运行查询时检查值稍好的计划。有时值得重复代码:You can use the
if
statement to control which statements are executed, but you can't use it to remove part of a query.One reason that it's not built that way is that the execution plan for the query would be different depending on the input, so a new execution plan would have to be created each time and could not be resused.
There are different ways to handle this, like using the
isnull
function to compare the value to itself if the varaible is null:Or checking for null before comparing:
You can always put the
if
statement around the query, which would give you two versions of the query, each with a slightly better plan than checking the value when running the query. Sometime that's worth the duplication of the code: