Cteate PROCEDURE [dbo].[SearchMatriculation]
@LSh varchar(50)= ' ',
@Niandu varchar(100)= ' ',
@SName varchar(100)= ' ',
@SClass varchar(100)= ' ',
@Subject varchar(100)= ' '
AS
BEGIN
Select * from dbo.Matriculation where [email protected] or 流水号 like '[email protected]% ' or 学生姓名 like '[email protected]% ' or [email protected] or [email protected];
END
数据库是SQL Server 2005。上面是我建立存储过程的脚本。没有达到我的要求,所以请教一下,我的目的是:上面有5个参数,查询时,可能只给其中某些参数值,其他的参数不参与到查询中,还有就是上面我写like查询时,对吗?后面是 '%参数名% ' 这样对吗?为什么运行时,明明包含那个字符串的记录都查不出来?
------解决方案--------------------
Select * from dbo.Matriculation where [email protected] or 流水号 like '% '[email protected]+ '% ' or 学生姓名 like '% '[email protected]+ '% ' or [email protected] or [email protected];
------解决方案--------------------
定义存储过程的时候,给传入参数一个默认值。调用的时候就可以不给了。例如:
create PROCEDURE sp_XXX
@SQL_FLAG char(01) ,
@arrive_zip_code varchar(06) = null,
...
like应该这样写:
Select * from dbo.Matriculation where [email protected] or 流水号 like '% ' + @LSh + '% ' or 学生姓名 like '% ' + @Sname + '% ' or [email protected] or [email protected];
------解决方案--------------------
其实上面的select 有问题,在这里不能使用or,不是说他有语法错误,而是查出来的数据应该不是我们想要的,因为已经使用like所以应该改成and
我已经把整个完整的建存储过程写好了,如下:
--判定原数据库中有无SearchMatriculation过程,有则先删除
if exists (select * from sysobjects where id = object_id( 'dbo.SearchMatriculation ') and type = 'P ')
drop procedure dbo.SearchMatriculation
GO
Create Procedure dbo.SearchMatriculation
@LSh varchar(50)= ' ',
@Niandu varchar(100)= ' ',
@SName varchar(100)= ' ',
@SClass varchar(100)= ' ',
@Subject varchar(100)= ' '
AS Begin
Select *
from dbo.Matriculation
where [email protected]
and 流水号 like '% '[email protected]+ '% '
and 学生姓名 like '% '[email protected]+ '% '
and [email protected]
and [email protected]
end
go
肯定不会有问题的