在查询中使用之间传递空值

时间:2016-07-07 05:52:41

标签: sql-server

我在T-SQL中编写存储过程以从下表中选择记录:

CREATE TABLE [dbo].[PHM_News_Entry]
(
    [NewsID] [int] IDENTITY(1,1) NOT NULL,
    [NewsTitle] [varchar](200) NULL,
    [NewsDate] [datetime] NULL,
    [NewsDescription] [nvarchar](max) NULL,
    [NewsDateEntry] [datetime] NULL,
    [NewAuthor] [varchar](200) NULL,
    [NewModificationDate] [datetime] NULL,
    [NewModifiedBy] [varchar](100) NULL,
    [Status] [varchar](50) NULL,
    [NewsAttatchmentPath] [nvarchar](max) NULL,
    [NewsImagePath] [nvarchar](max) NULL,
)

存储过程如下:

CREATE PROCEDURE Select_News 
    @NewsTitle VARCHAR(200), 
    @FromDate DATE,
    @ToDate DATE
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * 
    FROM PHM_News_Entry 
    WHERE (NewsTitle LIKE '%'+@NewsTitle+'%' OR @NewsTitle IS NULL) 
      AND NewsDate BETWEEN @FromDate AND @ToDate OR NewsDate IS NULL
END

参数即,@ NewsTitle,@ FrDate和@ToDate可以具有值或为NULL。如果所有3个参数或NULL,则应该没有选择记录,但如果其中一个具有非空值,则应选择一个或多个匹配记录。

如果我将NULL传递给所有3个参数,它按预期工作,即,不会选择任何记录,但它不会以其他方式工作,即,如果其中一个或其中一个具有非 - 空值。

请帮我写一下这个案例的正确查询。

谢谢和问候,

Shyam Singh

4 个答案:

答案 0 :(得分:0)

尝试此select查询

SELECT * 
FROM   phm_news_entry 
WHERE  ( newstitle LIKE '%' + @NewsTitle + '%' 
          OR @NewsTitle IS NULL ) 
       AND ( newsdate BETWEEN @FromDate AND @ToDate 
              OR @FromDate IS NULL 
              OR @ToDate IS NULL ) 
       AND ( @NewsTitle IS NOT NULL 
              OR @FromDate IS NOT NULL 
              OR @ToDate IS NOT NULL ) 

答案 1 :(得分:0)

使用此WHERE子句:

WHERE (NewsTitle LIKE '%'+@NewsTitle+'%' OR @NewsTitle IS NULL) AND
      (NewsDate BETWEEN COALESCE(@FromDate, CAST('1753-01-01' AS DATE)) AND
                       COALESCE(@ToDate, CAST('9999-12-31' AS DATE)) OR NewsDate IS NULL)

<强>解释

COALESCE(@FromDate, CAST('1753-01-01' AS DATE))

如果它不是@FromDate,它将使用NULL的值,或者如果它是NULL,它将使用SQL Server中可能的最小日期。因此,当@FromDateNULL时,此表达式将允许所有早于@ToDate的日期。类似的逻辑适用于其他COALESCE表达式。

答案 2 :(得分:0)

希望它适合你,

SELECT *,
FROM PHM_News_Entry
WHERE (NewsTitle LIKE '%'+@NewsTitle+'%'
       OR @NewsTitle IS NULL)
  AND (NewsDate BETWEEN COALESCE(@FromDate, CAST(NewsDate AS DATE)) AND COALESCE(@ToDate, CAST(NewsDate AS DATE)))
  OR (@NewsTitle IS NULL
      AND @FromDate IS NULL
      AND @ToDate IS NULL) END

答案 3 :(得分:-1)

如果其中一个params为null - 整个运算符为空 - if SomeThing between @d1 and NULL = nullnul or @d = null 使用isnull函数

FROM PHM_News_Entry 
WHERE  NewsDate BETWEEN isnull(@FromDate, '01-01-1753') AND isnull(@ToDate, '01-01-1753') OR NewsDate IS NULL