参数为null时更改条件

时间:2014-01-20 08:48:45

标签: sql sql-server sql-server-2008 stored-procedures

我有一个像这样的存储过程

CREATE PROCEDURE Table_Search

@param1 VARCHAR(100) = NULL,
@param2 VARCHAR(100) = NULL,
@param3 VARCHAR(100) = NULL
AS

SELECT * FROM Table1
WHERE
column1 LIKE '%' + @param1 + '%'
AND
column2 
IN 
(
    SELECT * FROM Table2
    WHERE
    CONTAINS(column3,@param2)
    AND
    column4 
    IN
    (
        SELECT * FROM 
        fn_SplitWords(@param3,',')
    )
)

我想要发生的是@param1 IS NOT NULL @param2 IS NULL AND @param3 IS NULL,存储过程就像:

CREATE PROCEDURE Table_Search
@param1 VARCHAR(100) = NULL,
@param2 VARCHAR(100) = NULL,
@param3 VARCHAR(100) = NULL
AS

SELECT * FROM Table1
WHERE
column1 LIKE '%' + @param1 + '%'

@param2 IS NOT NULL AND @param3 IS NULL时,存储过程将如下所示:

CREATE PROCEDURE Table_Search

@param1 VARCHAR(100) = NULL,
@param2 VARCHAR(100) = NULL,
@param3 VARCHAR(100) = NULL
AS

SELECT * FROM Table1
WHERE
column1 LIKE '%' + @param1 + '%'
AND
column2 
IN 
(
    SELECT * FROM Table2
    WHERE
    CONTAINS(column3,@param2)
)

我已经去过了 WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter valueStored procedure to handle null parameter 但我认为这是一个不同的情况。

这可能是什么方法?

2 个答案:

答案 0 :(得分:0)

您可以这样做:

SELECT * FROM Table1
WHERE
column1 LIKE '%' + ISNULL(@param1, column1) + '%' AND
column2 LIKE '%' + ISNULL(@param2, column2) + '%' AND
...

如果设置了参数,则会对每个字段进行过滤。

答案 1 :(得分:0)

您可以动态构建您的sql语句,然后执行SQL proc来执行类似这样的查询...

DECLARE @Sql NVARCHAR(MAX);

SET @Sql = N'SELECT * FROM Table1
            WHERE 1 = 1 '

IF (@param1 IS NOT NULL)
BEGIN
  SET @Sql = @Sql + N' AND column1 LIKE ''%@param1%'''
END

IF (@param2 IS NOT NULL)
BEGIN
SET @Sql = @Sql + N' AND column2  IN (
                                        SELECT * FROM Table2
                                        WHERE
                                        CONTAINS(column3,@param2)
                                     )'
END

IF (@param3 IS NOT NULL)
BEGIN
 SET @Sql = @Sql + N' AND column4 
                                IN
                                (
                                    SELECT * FROM 
                                    fn_SplitWords(@param3,'','')
                                )
                            '
END


EXECUTE sp_executesql @Sql
                    , N'@param1 VARCHAR(100),@param2 VARCHAR(100),@param3 VARCHAR(100)'
                    , @param1, @param2, @param3