5

我有一个表名学生有 (studentId, StudentName,Address,PhoneNo)

我为用户提供了一个过滤器,可以从 Combobox 中仅选择 StudentId 以获取学生的详细信息...并生成报告。

我编写了以下查询来获取学生详细信息:

(select * from Students where StudentId = stdId)

这里 stdId 是我从代码传递的参数

"ALL" 如果我选择单个studentId,它工作正常......但是在用户选择Comobobox中,如果用户从组合框中选择我也提供了All我想显示所有学生的详细信息

stdId那么如果用户选择我应该传入什么All

我在 C# 中使用了内联查询(不使用 SQL 存储过程)

4

4 回答 4

6

如果用户选择全部,则传递NULL@StudentId并将您的查询更改为:

select *
from Students
where (StudentId=@StudentId OR @StudentId IS NULL)
于 2012-10-24T11:08:07.460 回答
6

你可以这样做。

SELECT * from Students s
WHERE s.studentId = ISNULL(@StudentId,s.studentId) 

在组合框中选择“全部”时,在 @studentid 参数中传递 null。如果您不能在参数中传递 null 则传递 -1 或任何不能包含在您的组合框选项中的内容,并像这样:(如果 -1= All)

 SELECT * from Students s
 WHERE s.studentId = @StudentId or @StudentId=-1

你也可以试试Curt给出的答案。

于 2012-10-24T11:16:28.367 回答
4

在您的存储过程标头中,更改@StudentId 的定义,以便它可以作为NULL 传递。

ALTER PROCEDURE dbo.WhateverYourProcedureIsCalled( @StudentId int  = null )

然后按如下方式更改您的 WHERE 子句

...

SELECT * from Students
WHERE @StudentId IS NULL OR StudentId = @StudentId

在您的代码中,如果传递了 ALL,则可以省略设置 @StudentId 参数值的部分。如果未通过,SQL Server 将使用默认值。

于 2012-10-24T11:08:34.743 回答
1

如果查询中包含 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
}
于 2012-10-24T11:10:30.173 回答