我想吧SQL语句移到存储过程里,但我的where条件是动态的,有的条件存在,有的还不存在请问我在写存储过程时where条件怎么处理?并且order by 后跟个传进来的变量也报错! 比如: where name=@name and id=@id 请大家详细解说,并附上如何写的?比如上面,有时候我的@name有值为张三,而@id没值,,此时怎么让存储过程SQL语句是正确的?而不会出现where name=‘张三’ and id=‘’我想要的是where name=‘张三’
where name = isnull(@name,name) and id = ISNULL(@id,id)如果你的某些列有可能为null的话,那么需要用下面的语句where isnull(name,'~~') = isnull(@name,isnull(name,'~~')) and id = ISNULL(@id,id)