How do I create a stored procedure that will optionally search columns?

前端 未结 10 684
醉话见心
醉话见心 2020-12-08 08:30

I\'m working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria

10条回答
  •  粉色の甜心
    2020-12-08 09:15

    Using the COALESCE method has a problem in that if your column has a NULL value, passing in a NULL search condition (meaning ignore the search condition) will not return the row in many databases.

    For example, try the following code on SQL Server 2000:

    CREATE TABLE dbo.Test_Coalesce (
        my_id   INT NOT NULL IDENTITY,
        my_string   VARCHAR(20) NULL )
    GO
    INSERT INTO dbo.Test_Coalesce (my_string) VALUES (NULL)
    INSERT INTO dbo.Test_Coalesce (my_string) VALUES ('t')
    INSERT INTO dbo.Test_Coalesce (my_string) VALUES ('x')
    INSERT INTO dbo.Test_Coalesce (my_string) VALUES (NULL)
    GO
    DECLARE @my_string  VARCHAR(20)
    SET @my_string = NULL
    SELECT * FROM dbo.Test_Coalesce WHERE my_string = COALESCE(@my_string, my_string)
    GO
    

    You will only get back two rows because in the rows where the column my_string is NULL you are effective getting:

    my_string = COALESCE(@my_string, my_string) =>
    my_string = COALESCE(NULL, my_string) =>
    my_string = my_string =>
    NULL = NULL
    

    But of course, NULL does not equal NULL.

    I try to stick with:

    SELECT
         my_id,
         my_string
    FROM
         dbo.Test_Coalesce
    WHERE
         (@my_string IS NULL OR my_string = @my_string)
    

    Of course, you can adjust that to use wild cards or whatever else you want to do.

提交回复
热议问题