传递null参数时出错

时间:2016-06-08 12:37:51

标签: sql sql-server null parameter-passing

如果创建的日期时间为空或者没有值,我想返回整个表格。如果它包含日期,我想返回大于该日期的表数据。我在下面提交了一个代码,但是当有参数时它会提供数据,但它显示的错误类似于此程​​序SelectRotarian_AllByCreatedDatetime 过程或函数SelectRotarian_AllByCreatedDatetime需要参数@createdDateTime,这是未提供的。

(1行受影响)

ALTER PROCEDURE [dbo].[SelectRotarian_AllByCreatedDatetime]
    @createdDateTime varchar(50)
AS
BEGIN

    SET NOCOUNT ON;

    if (Coalesce(@createdDateTime,'') = '')
    begin
           select [id]
      ,[surName]
      ,[firstName]
      ,[secondName]
      , [address]
      , [gender]
      ,[picture]
      ,[email]
      ,[phoneNumber]
      ,[DOB]
      ,[vocation]
      ,[bloodGroup_id]
      ,[club_id]
      ,[createdDateTime]
    FROM [rotary_rotarian]
     end 
     else 
     begin

           SELECT[id]
      ,[surName]
      ,[firstName]
      ,[secondName]
      , [address]
      , [gender]
      ,[picture]
      ,[email]
      ,[phoneNumber]
      ,[DOB]
      ,[vocation]
      ,[bloodGroup_id]
      ,[club_id]
      ,[createdDateTime]
    FROM [rotary_rotarian]
    where [createdDateTime] > CAST(@createdDateTime AS DateTime)
      end
     END

所以请帮帮我

2 个答案:

答案 0 :(得分:3)

而不是:

ALTER PROCEDURE [dbo].[SelectRotarian_AllByCreatedDatetime]
    @createdDateTime varchar(50)
AS
BEGIN

允许您的参数为可空/可选,如:

ALTER PROCEDURE [dbo].[SelectRotarian_AllByCreatedDatetime]
    @createdDateTime DateTime = NULL
AS
BEGIN

另请注意,您应该传递datetime作为datetime,而不是varchar

然后:

if (Coalesce(@createdDateTime,'') = '')

可以成为

if (@createdDatetime IS NULL)

答案 1 :(得分:1)

错误消息显示:使用当前存储过程,您必须传递参数。即使传递空参数或NULL参数,仍然必须传递参数。获得错误的唯一方法是在不传递参数的情况下调用该过程。

如果您希望存储过程即使没有传递参数也能工作,那么您必须为参数提供一个默认值,如下所示:

ALTER PROCEDURE [dbo].[SelectRotarian_AllByCreatedDatetime]
    @createdDateTime varchar(50) = ''
AS