【问题标题】:Issue Related to where clause in SQL Server与 SQL Server 中的 where 子句相关的问题
【发布时间】:2012-10-24 11:04:24
【问题描述】:

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

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

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

(select * from Students where StudentId = stdId)

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

如果我选择单个 studentId 则效果很好....但是在用户选择组合框中我还提供了"ALL" 如果用户从组合框中选择 All 我想显示所有学生的详细信息

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

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

【问题讨论】:

  • 只写一个没有where子句的查询案例,用于用户全选?对于所有其他情况,请使用此查询

标签: c# sql-server


【解决方案1】:

你可以这样做。

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给出的答案。

【讨论】:

    【解决方案2】:

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

    select *
    from Students
    where (StudentId=@StudentId OR @StudentId IS NULL)
    

    【讨论】:

      【解决方案3】:

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

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

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

      ...

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

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

      【讨论】:

        【解决方案4】:

        如果查询中包含 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
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-06
          • 1970-01-01
          • 2013-04-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多