0

我怎样才能使这个 If 语句跳到下面的 if 语句?我尝试了 else if,then,但它不起作用。无论输入是否传递给变量,我都希望它显示。

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 )
4

1 回答 1

0

处理未知数量条件的常用方法是使第一个条件WHERE 1=1或一些良性条件,例如WHERE id IS NOT NULL当已知 id 不可为空时。

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 )
于 2012-10-17T08:18:19.157 回答