繁体   English   中英

SQL 查询 where 子句可以为空或包含值

[英]SQL Query when where clause could be empty or contain value

我想要一个 select 查询,该查询能够 select 一个可能存在也可能不存在于 where 子句中的值。 架构:


----------------------------------
studentid|firstname|lastname|major

我的 select 条款是

select * from students where studentid?={param} AND firstname?={param} AND lastname?={param} AND major?={param};

我打了一个问号,因为我的意思是说我可以在 where 子句中传递一个值,也可能不传递。 它可能是

select * from students where studentid?=34344 AND firstname?="john" AND lastname?="smith" AND major?="";

select * from students where studentid?=34344 AND firstname?="john" AND lastname?="smith" AND major?="english";

有没有一种方法可以在没有存储过程的情况下轻松做到这一点?

您可以通过使用变量并像这样检查 null 来做到这一点:

Declare @StudentId nvarchar(100) --can be null or evaluated

select * from students 
where (@StudentId is null or studnetId= @StudentId) AND -- for other properties as well

另一种选择是使用动态 sql ,首先你必须构建你的 sql 查询然后执行它(我不喜欢它)

如果可能,您可以在应用程序端处理它:

string query= "select * from students where 1=1 /*trick for adding more conditions*/"

if(numberId is not null)
   query += "AND studentId= {numberId} ";

//for other conditions ...

暂无
暂无

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

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