写了一个存储过程,带有多个参数,希望的是如果某个参数为空则不参与查询条件,但测试不成功不知道怎么回事
create proc 
@vehicleid nchar(12),
@dn numeric(8,0)
as 
select * from t1 where vehicleid like '%'+ isnull(@vehicleid,vehicleid) +'%' and dn = isnull(@dn,dn)没有提示错误,只是查询的结果不正确。

解决方案 »

  1.   

    你这样写,当传入参数为空时,where条件就类似where  1=1 是恒成立的,结果当然不对
      

  2.   

    create proc  pp
    @vehicleid nchar(12),
    @dn numeric(8,0)
    as 
    if @dn is null or @dn='' 
    select * from t1 where vehicleid like '''%'+ @vehicleid +'%'''
    end
    else if  @vehicleid is null or @vehicleid='' 
    select * from t1 where dn=@dn
    end
      

  3.   

    create proc  pp
    @vehicleid nchar(12),
    @dn numeric(8,0)
    as 
    if @dn is null or @dn='' 
    begin
    select * from t1 where vehicleid like '''%'+ @vehicleid +'%'''
    end
    else if  @vehicleid is null or @vehicleid='' 
    begin
    select * from t1 where dn=@dn
    end
      

  4.   

    isnull((@vehicleid,vehicleid)这个是可以的,你自己调试一下是不是没数据等问题
      

  5.   

    刚测试了下,用isnull你那么写是可以。多谢DBA吉哥提醒
      

  6.   

    估计是like的问题,直接写成=的话,查询结果是正确的。
      

  7.   

    create proc  pp --你此处没有存过过程名称
    @vehicleid nchar(12),
    @dn numeric(8,0)
    as 
    select * from t1 
    where vehicleid like '''%'+ isnull(@vehicleid,vehicleid) +'%''' and dn = isnull(@dn,dn)你再试试
      

  8.   

    估计是like的问题,直接写成=的话,查询结果是正确的。但是需要用到like。
      

  9.   

    目测单引号加多了like '%'+ isnull(@vehicleid,vehicleid) +'%'
      

  10.   


    --sql2008 执行的
    declare @a nchar(12),
    @b nvarchar(10)
    set @a='1'
    set @b='2'
    print @a+'==='
    print @b+'==='
    --执行结果
    --1           ===
    --2===
    --楼主悟出点什么木有?
      

  11.   

    create procedure dbo.p_InsertTest
        (
        @vehicleid varchar(12),
    @dn numeric(8,0)
        )
        as 
        select * from t1 where vehicleid like '%'+ isnull(@vehicleid,vehicleid) +'%' and dn = isnull(@dn,dn)