像不适用于特定种类的存储过程

时间:2019-03-30 14:35:49

标签: asp.net sql-server

我创建了一个存储过程,该存储过程使用ASP.NET中的表单来创建对数据库中成千上万本书的关键字搜索。

问题是我已经从另一个开发人员那里继承了代码,并且必须使用她的代码。我无法重写存储过程。

结果,我必须找到一种将LIKE运算符添加到存储过程的以下部分的方法:

 Books      = @Books    OR @Books    IS NULL

这是因为@Books是用户在其中输入关键字搜索的表单的一部分。我已经查找了如何在存储过程中使用LIKE运算符,但是没有任何内容适用于此类代码。

下面列出了完整的存储过程:

 Create Procedure spSearchAuthors
 @FirstName nvarchar(100) = NULL,
 @LastName nvarchar(100) = NULL,
 @Books nvarchar(50) = NULL
 As
 Begin

 Select FirstName, LastName, Books from Authors where
 (FirstName = @FirstName OR @FirstName IS NULL) AND
 (LastName  = @LastName  OR @LastName  IS NULL) AND
 (Books      = @Books    OR @Books    IS NULL) 
 End
 Go

1 个答案:

答案 0 :(得分:0)

LIKE具有简单的语法:%_[...]

在这种情况下,您可以保持简单。
通过在字符串变量的两端添加%

CREATE Procedure spSearchAuthors
 @FirstName NVARCHAR(100) = NULL,
 @LastName NVARCHAR(100) = NULL,
 @Books NVARCHAR(50) = NULL
AS
BEGIN

    SELECT FirstName, LastName, Books 
    FROM Authors 
    WHERE (@FirstName IS NULL OR FirstName LIKE '%'+@FirstName+'%') 
      AND (@LastName IS NULL OR LastName  LIKE '%'+@LastName+'%') 
      AND (@Books IS NULL OR Books LIKE '%'+@Books+'%');

END;
GO

使用动态SQL更复杂。

CREATE Procedure spSearchAuthors
 @FirstName NVARCHAR(100) = NULL,
 @LastName NVARCHAR(100) = NULL,
 @Books NVARCHAR(50) = NULL
AS
BEGIN

    DECLARE @DynSql NVARCHAR(800);
    DECLARE @ParmDefinition NVARCHAR(100);

    SET @DynSql = N'SELECT FirstName, LastName, Books FROM Authors';

    IF @FirstName IS NOT NULL
    BEGIN 
      SET @DynSql += CHAR(10)+'WHERE FirstName LIKE @FirstName';
      SET @FirstName = N'%'+@FirstName+N'%';
    END;

    IF @LastName IS NOT NULL
    BEGIN
      IF @FirstName IS NULL 
        SET @DynSql += CHAR(10)+'WHERE ';
      ELSE 
        SET @DynSql += CHAR(10)+'AND ';

      SET @DynSql += 'LastName LIKE @LastName';
      SET @LastName = N'%'+@LastName+N'%';
    END;

    IF @Books IS NOT NULL 
    BEGIN
      IF @FirstName IS NULL AND @LastName IS NULL
        SET @DynSql += CHAR(10)+'WHERE ';
      ELSE
         SET @DynSql += CHAR(10)+'AND ';

      SET @DynSql += 'Books LIKE @Books';
      SET @Books = N'%'+@Books+N'%';
    END;   

    SET @ParmDefinition = N'@FirstName NVARCHAR(102), @LastName NVARCHAR(102), @Books NVARCHAR(52)';  

    EXECUTE sp_executesql @DynSql, @ParmDefinition, 
      @FirstName = @FirstName, 
      @LastName = @LastName, 
      @Books = @Books;
END;
GO