简体   繁体   English

sql查询参数是否为空

[英]sql query if parameter is null

I am trying to write a stored procedure in SQL 2008 R2 and am having major issues. 我正在尝试在SQL 2008 R2中编写存储过程,并且遇到了主要问题。 The query behind it should pull first name, last name, balance, & case type. 它后面的查询应提取名字,姓氏,余额和大小写类型。 Problem is, some people (ie, results) will have the same name. 问题是,某些人(即结果)将具有相同的名称。 So I added a parameter @DOB to weed them down. 所以我添加了一个参数@DOB来清除它们。 If there are several people with the same name, the user should be able to enter the date of birth and only get that person back. 如果有几个同名的人,则用户应该能够输入出生日期并且只能将其找回。 Problem is...I can't get it to work. 问题是...我无法正常工作。 Here's my query - warning I use aliases I apologize if its confusing to read: 这是我的查询-警告:如果我混淆阅读,我会使用别名道歉:

SELECT cs.last_name ,
       cs.first_name ,
       cs.dob,
       cb.assessment_balance_due ,
       cb.case_number,
       ct.case_type_title
FROM vw_customer_service cs
INNER JOIN vw_case_balance cb ON cs.case_ID = cb.case_ID
INNER JOIN [case] on cs.case_ID = [case].case_ID
INNER JOIN cd_case_type ct ON [case].case_type_ID = ct.case_type_ID
WHERE **--(cs.dob =  case when @dob is null then cs.dob else @dob end )**  and
 cb.assessment_balance_due > 0
  AND cs.last_name = @LastName
  AND cs.first_name = @FirstName
  AND party_type_ID = 28 --defendant

  AND (@dob IS NULL)
GROUP BY 
         cs.case_ID, cs.last_name, cs.first_name , cb.Assessment_Balance_Due,DOB, cb.case_number, ct.case_type_title

This will only return data if the user puts in the DOB, but I want that to just be an option. 如果用户放入DOB,这只会返回数据,但我希望这只是一个选择。 How do I filter a result set based on one parameter OR not filter at all if the parameter is left off? 如何根据一个参数过滤结果集,或者如果不设置该参数,则根本不过滤? Thanks in advance! 提前致谢!

您可以这样做:

where (@dob is null or cs.dob = @dob) ...

Try this... 尝试这个...

SELECT  cs.last_name , cs.first_name , cs.dob, cb.assessment_balance_due , cb.case_number, ct.case_type_title
from vw_customer_service cs 
INNER JOIN vw_case_balance cb on cs.case_ID = cb.case_ID
INNER JOIN [case] on cs.case_ID = [case].case_ID 
INNER JOIN cd_case_type ct on [case].case_type_ID = ct.case_type_ID


where (@dob is null or cs.dob=@dob)
and cb.assessment_balance_due > 0 
and cs.last_name = @LastName 
and cs.first_name = @FirstName
and party_type_ID = 28 --defendant 
--and (@dob is null)
group by cs.case_ID, cs.last_name, cs.first_name , cb.Assessment_Balance_Due,DOB, cb.case_number, ct.case_type_title

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

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