如何使这个IF语句跳到另一个if语句?

时间:2012-10-17 07:50:05

标签: sql-server stored-procedures

如何使这个If语句跳到下面的if语句?如果那么我试过了,但是它不起作用。无论是否将输入传递给变量,我都希望它显示。

declare @sql varchar(8000)
declare @sql_where varchar(8000)

declare @ww varchar(10)
declare @plant varchar(10)
declare @plnr_id varchar(10)

set @plant = 'CS58'
set @ww = '201240'  
set @plnr_id = 'G37'

set @sql_where = 'where'
set @sql = 'select * from  rout_sub_doi '

if len(@plant) > 0 
    set @sql_where = @sql_where + ' plant = ''' + @plant + ''' '

if len(@ww) > 0
    set @sql_where = @sql_where + 'AND sys_intel_ww = ''' + @ww + ''' '

if len(@plnr_id) > 0 

    set @sql_where = @sql_where + ' AND plnr_id = ''' + @plnr_id + ''' '


print @sql
print @sql_where

exec (@sql + @sql_where )

1 个答案:

答案 0 :(得分:0)

处理未知数量的条件的常用方法是,当已知id不可为空时,将WHERE 1=1或其他内容设为良性,例如WHERE id IS NOT NULL

declare @sql varchar(8000)
declare @sql_where varchar(8000)

declare @ww varchar(10)
declare @plant varchar(10)
declare @plnr_id varchar(10)

set @plant = 'CS58'
set @ww = '201240'  
set @plnr_id = 'G37'

set @sql_where = ''
set @sql = 'select * from rout_sub_doi where 1=1 '

if len(@plant) > 0 
    set @sql_where = @sql_where + 'AND plant = ''' + @plant + ''' '

if len(@ww) > 0
    set @sql_where = @sql_where + 'AND sys_intel_ww = ''' + @ww + ''' '

if len(@plnr_id) > 0 
    set @sql_where = @sql_where + 'AND plnr_id = ''' + @plnr_id + ''' '

print @sql
print @sql_where

exec (@sql + @sql_where )