存储过程中的多个CASE

时间:2017-05-06 12:03:52

标签: sql-server stored-procedures case

CREATE PROCEDURE [dbo].[PROC_VuReg]   
     @PACKAGEDESCR VARCHAR(50),
     @VOUCHERFROMDT VARCHAR(20),
     @VOUCHERTODT VARCHAR(20),
     @STATUS VARCHAR(10),
     @RefNo VARCHAR(10)
AS
BEGIN
    SET @sQRY = 'SELECT * FROM VuReg WHERE PACKAGEDESCR = ''' + @PACKAGEDESCR  +
                 ''' AND VOUCHERDT BETWEEN ''' + @VOUCHERFROMDT + ''' AND ''' +  @VOUCHERTODT + 
                 ''' AND SUBACTIVITY = CASE WHEN LEN(''' + @RefNo + ''') > 0 THEN ''' + @RefNo + ''' ELSE SUBACTIVITY END AND WDNO = CASE WHEN ''' + @STATUS  + ''' =''NULL'' THEN IS NULL WHEN '''+ @STATUS   + ''' =  ''NOT NULL'' THEN  IS NOT NULL WHEN '''+ @STATUS   + ''' =  '''' THEN  WDNO END '

   --print @sqry
   EXEC sp_executesql @sqry
END

在上面的过程中,在添加参数@Status之前,一切都运行良好。

如果@statusNULL,则条件为

SELECT * FROM VuReg WHERE WDNO IS NULL

如果@statusNOT NULL,则条件为

SELECT * FROM VuReg WHERE WDNO IS NOT NULL

如果@status'',则条件为

SELECT * FROM VuReg WHERE WDNO = WDNO

{期待所有记录}

1 个答案:

答案 0 :(得分:1)

您可以在没有动态sql的情况下执行此操作。

create procedure dbo.proc_VuReg
    @packagedescr varchar(50)
  , @voucherfromdt varchar(20)
  , @vouchertodt varchar(20)
  , @status varchar(10)
  , @RefNo varchar(10)
as
begin;
set nocount on;

select  * 
from VuReg 
where packagedescr = @packagedescr  
  and voucherdt between @voucherfromdt and @vouchertodt 
  and (subactivity = @RefNo or @RefNo is null)
  and ( 
       (@status = 'null' and wdno is null)
    or (@status = 'not null' and wdno is not null)
    or @status = ''
    )
option(recompile) /* generates a new execution plan for each execution to help accommodate the conditional logic in the where clause */
end;

如果您仍想动态,请正确使用。从这些开始: