简体   繁体   English

SQL IF else在where语句中

[英]SQL IF else in where statement

ALTER PROCEDURE [dbo].[sp_CourseEvalRpt_2]
    @coursetitle varchar(100) = null,
    @datestart varchar(8),
    @dateend varchar(8)
AS
    select distinct 
        t_empname, t_leader, T_Dept, t_submit 
    from 
        tbltrain
    where 
        t_category like 'course%' 
        and 
           if (@coursetitle <> '') t_course = @coursetitle end

How can I eliminate the SQL where criteria when parameter name @coursetitle is empty? 当参数名称@coursetitle为空时,如何消除SQL where条件? I don't want to add the t_course condition when @coursetitle is empty, so system will display all data rather than set the t_course=''. 当@coursetitle为空时,我不想添加t_course条件,因此系统将显示所有数据而不是设置t_course =''。

Try changing your sql to this: 尝试将您的sql更改为此:

select distinct t_empname,
       t_leader,
       T_Dept,
       t_submit 
  from tbltrain
 where t_category like 'course%' 
   and ( (@coursetitle<>''and t_course=@coursetitle) 
         or @coursetitle='')

You can simplify the where clause to: 您可以将where子句简化为:

where t_category like 'course%' and
      (@coursetitle = '' or t_course = @coursetitle) 

If you used NULL instead of an empty string for @coursetitle , you could phrase it as: 如果对@coursetitle使用NULL而不是空字符串,则可以将其表示为:

where t_category like 'course%' and
      t_course = coalesce(@coursetitle, t_course)

How about using dynamic SQL ? 如何使用动态SQL? so that you can perform a clear IF ELSE condition. 这样您就可以执行清晰的IF ELSE条件。

Just add SQLQuery variable for the SQL query and use dynamic SQL 只需为SQL查询添加SQLQuery变量并使用动态SQL

ALTER PROCEDURE [dbo].[sp_CourseEvalRpt_2]

@coursetitle varchar(100)=null,
@datestart varchar(8),
@dateend varchar(8),
@SQLQuery varchar(max) -->> Additional variable for dynamic SQL
AS

SET @SQLQuery = 'select distinct t_empname,t_leader,T_Dept,t_submit 
                 from tbltrain where t_category like course%'

IF ISNULL(@coursetitle,'') <> ''
    BEGIN
       SET @SQLQuery = @SQLQuery + 'AND t_course = ' + @coursetitle 
    END

EXEC (@SQLQuery)

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

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