3 回答
TA贡献2019条经验 获得超9个赞
OPTION (RECOMPILE)
OR
(@LastName IS NULL OR LastName= @LastName)
CREATE PROCEDURE spDoSearch @FirstName varchar(25) = null, @LastName varchar(25) = null, @Title varchar(25) = nullAS BEGIN SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE (@FirstName IS NULL OR (FirstName = @FirstName)) AND (@LastName IS NULL OR (LastName = @LastName )) AND (@Title IS NULL OR (Title = @Title )) OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later END
TA贡献1802条经验 获得超6个赞
.忽略紧凑型代码,忽略对重复代码的担忧.
CREATE PROCEDURE spDoSearch @FirstName varchar(25) = null, @LastName varchar(25) = null, @Title varchar(25) = nullASBEGIN IF (@FirstName IS NOT NULL AND @LastName IS NULL AND @Title IS NULL) -- Search by first name only SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE FirstName = @FirstName ELSE IF (@FirstName IS NULL AND @LastName IS NOT NULL AND @Title IS NULL) -- Search by last name only SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE LastName = @LastName ELSE IF (@FirstName IS NULL AND @LastName IS NULL AND @Title IS NOT NULL) -- Search by title only SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE Title = @Title ELSE IF (@FirstName IS NOT NULL AND @LastName IS NOT NULL AND @Title IS NULL) -- Search by first and last name SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE FirstName = @FirstName AND LastName = @LastName ELSE -- Search by any other combination SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE (@FirstName IS NULL OR (FirstName = @FirstName)) AND (@LastName IS NULL OR (LastName = @LastName )) AND (@Title IS NULL OR (Title = @Title ))END
TA贡献1797条经验 获得超6个赞
CREATE PROCEDURE spDoSearch @FirstName varchar(25) = null, @LastName varchar(25) = null, @Title varchar(25) = nullAS BEGIN SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE (@FirstName IS NULL OR FirstName = @FirstName) AND (@LastNameName IS NULL OR LastName = @LastName) AND (@Title IS NULL OR Title = @Title)END
添加回答
举报