How can I use optional parameters in a T-SQL stored procedure?

后端 未结 6 733
天涯浪人
天涯浪人 2020-11-22 05:56

I am creating a stored procedure to do a search through a table. I have many different search fields, all of which are optional. Is there a way to create a stored procedur

6条回答
  •  醉酒成梦
    2020-11-22 06:51

    You can do in the following case,

    CREATE PROCEDURE spDoSearch
       @FirstName varchar(25) = null,
       @LastName varchar(25) = null,
       @Title varchar(25) = null
    AS
      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
    

    however depend on data sometimes better create dynamic query and execute them.

提交回复
热议问题