简体   繁体   English

如何在存储过程中编写if条件案例

[英]how to write an if condition case in stored procedure

i have an table where i am passing 5 paramter 我有一张桌子,我要传递5个参数

table name=" image"
parameter
@imageID,
@imageName,
@imageDirectory,
@imageResource,

from the front end [from page that is from textbox control] if they didnot send any values to stored procedue then i should do an simple Query condition1: 从前端[从文本框控件的页面]开始,如果它们没有向存储过程发送任何值,那么我应该做一个简单的查询条件1:

 select  * From image

condition 2: if they send any value to these above parameter then collect those vlaues and retrive result based on the parameted sent 条件2:如果他们向上述参数发送了任何值,则收集参数并根据发送的参数检索结果

condition 3: here they might send values to any of the of the parameter in that condition select values for that parameter . 条件3:在这种情况下,它们可能会向该参数的任何一个发送值,为此条件选择该参数的值。 for the parameter which they have not send values we can send 'null' or ' ' 对于他们没有发送值的参数,我们可以发送'null'或''

so based on that retrive the result 所以根据那个检索结果

so how write an Stored procedure for such an condition. 那么如何为这种情况编写存储过程。 handling all the three condition 处理所有三个条件

anyhelp would be really great thank you anyhelp真的很棒,谢谢

Try something along these lines: 尝试以下方法:

SELECT * FROM IMAGE i
WHERE 1=1 
AND (@ImageID IS NULL OR i.ImageId = @ImageID )
AND (@ImageName IS NULL OR i.ImageName = @ImageName )
AND (@ImageDirectory IS NULL OR i.ImageDirectory = @ImageDirectory)
AND (@ImageResource IS NULL OR i.ImageResource = @ImageResource)

You can also use the IsNull (transact-SQL specific) or Coalesce (SQL-92 standard) function, as in: 您还可以使用IsNull (特定于Transact-SQL)或Coalesce (SQL-92标准)函数,如下所示:

 Select * From Table
 Where imageId = Coalesce(@ImageId, imageId)
    And imageName = Coalesce(@imageName,imageName)
    etc.  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM