1

我正在执行这样的过程:

EXEC myProcedure  @name = 'Smith',  @dateDeleted = NULL

我需要所有没有删除日期的史密斯。

这是程序:

CREATE PROCEDURE [dbo].[myProcedure]
  @name VARCHAR(8000) = NULL
 ,@dateDeleted VARCHAR(8000) = NULL

AS
BEGIN
 SET NOCOUNT ON;
    WITH t 
    (name
    ,dateDeleted
    )

AS
(
    SELECT DISTINCT 
    name,dateDeleted FROM mytable
     WHERE 
  (@name IS NULL OR @name = name)
   AND (@dateDeleted IS NULL OR CONVERT(DATETIME, @dateDeleted, 102) = dateDeleted)

)

执行后,我拥有所有的史密斯,但它没有注意 dateDeleted = NULL .. 无论他们是否有删除的日期,我都会得到所有的史密斯

我怎样才能解决这个问题?

谢谢

4

2 回答 2

2

在您的请求中,如果您传递 NULL,则条件始终为真。试试这个 WHERE 子句和COALESCE表达式:

   WHERE (@name IS NULL OR @name = name)
   AND (COALESCE(@dateDeleted, dateDeleted) IS NULL 
     OR CONVERT(DATETIME, @dateDeleted, 102) = dateDeleted)
于 2013-02-21T13:19:53.177 回答
0

您需要设置 ansi nulls on

执行:

set ansi_nulls on

然后执行查询。

这是对此行为的解释

http://msdn.microsoft.com/en-us/library/ms188048.aspx

于 2013-02-21T13:02:55.463 回答