动态sql语句。一个存储过程中,根据一个参数(如@plant)决定where条件。@plant如果为空,则不根据Plant查询,查询所有的数据;如果不为空,则根据Plant查询,查询该条件下的数据。如果直接Plant=@plant,当@plant为空时,这样的操作会导致查询的结果为空。
if(isnull(@plant,'')='') begin select * from Product where Product=@Product end else begin select * from Product where Product=@Product and Plant=@Plant end
一个参数相对容易一些,但是where条件后面的参数不是一个而是多个。而这些参数与@plant类似,为空则查询所有;不为空则按条件查询。如果照葫芦画瓢,在以上后面sql写类似sql。于是,查询的结果有多个,都不是多个条件下并行查询而得出的一个结果。此时,采取动态sql,declare @sql varchar(1000),然后根据参数判断是否为空,set @sql=@sql+'********'。最后,exec(@sql)。
然而,上面的方法还是略显复杂,现介绍一种简单的处理方法。
select * from Product where Product=@product and (Plant=@plant or @plant='')
其实,可以把where后面的条件看成这样 where (Product=@product and Plant=@plant) or (Product=@product and @plant=''),即相当于两个条件下的并集。当@plant为空时,where (Product=@product and Plant=@plant) 查询出来的结果为空,此时@plant=''为true,where Product=@product查询的结果就是查询所有的plant的结果。这样并集就是@plant为空,查询所有;当@plant不为空时,where (Product=@product and Plant=@plant)查询的结果就是对应条件下的记录集,此时@plant=''为flase,where (Product=@product and Plant=@plant)此时查询的结果为空。这样并集就是@plant不为空,按条件查询。多个参数也采取相似的处理就相对简单多了。
posted on
浙公网安备 33010602011771号