C# 与SQL Server中的where子句相关的问题
我有一个表名学生有studentId,StudentName,Address,PhoneNo 我已经为用户提供了一个过滤器,可以从Combobox中只选择StudentId来获取学生的详细信息。。。并生成报告 我编写了以下查询以获取学生详细信息:C# 与SQL Server中的where子句相关的问题,c#,sql-server,C#,Sql Server,我有一个表名学生有studentId,StudentName,Address,PhoneNo 我已经为用户提供了一个过滤器,可以从Combobox中只选择StudentId来获取学生的详细信息。。。并生成报告 我编写了以下查询以获取学生详细信息: (select * from Students where StudentId = stdId) 这里stdId是我从代码传递的一个参数 如果我选择单身学生ID,效果很好。。。。但在“用户选择”组合框中,我还提供了“如果用户从组合框中选择全部”,我希
(select * from Students where StudentId = stdId)
这里stdId是我从代码传递的一个参数
如果我选择单身学生ID,效果很好。。。。但在“用户选择”组合框中,我还提供了“如果用户从组合框中选择全部”,我希望显示所有学生的详细信息
那个么,若用户选择All,那个么我应该传入stdId什么呢
我在C中使用了内联查询,没有使用SQL存储过程如果用户选择all,则将NULL传递给@StudentId并将查询更改为:
select *
from Students
where (StudentId=@StudentId OR @StudentId IS NULL)
在存储过程头中,更改@StudentId的定义,使其可以作为NULL传递
ALTER PROCEDURE dbo.WhateverYourProcedureIsCalled( @StudentId int = null )
然后将WHERE子句更改如下
在代码中,如果传递了ALL,则可以省略设置@StudentId参数值的部分。如果未通过,SQL Server将使用默认值。如果查询中包含where子句,则还需要提供有效的参数值,因此在包含where子句时无法获取所有学生 您需要根据组合框中选择的值区分查询。您可以执行以下操作
int studentId = 0;
//Where selectedValue comes from your combobox
Int32.TryParse(selectedValue, out studentId);
var query = "select * from Students";
if (studentId > 0)
{
query = query + " where StudentId = @StudentId";
//Remember to add studentId as parameter value
}
你可以这样做
SELECT * from Students s
WHERE s.studentId = ISNULL(@StudentId,s.studentId)
在组合框中选择“全部”时,在@studentid参数中传递null。若您不能在参数中传递null,那个么就传递-1或任何不能包含在combox选项中的内容,并按如下方式执行:If-1=All
SELECT * from Students s
WHERE s.studentId = @StudentId or @StudentId=-1
您也可以尝试Curt给出的答案。只需编写一个案例,其中包含一个不带where子句的查询,说明用户何时选择all?对于所有其他情况,请使用此查询
SELECT * from Students s
WHERE s.studentId = @StudentId or @StudentId=-1