How to declare parameters for a stored procedure.

  • Edited to correct syntax:

    Where...And siteglobalcode =

    Case 

        When @p_sitecode is null then siteglobalcode 

        Else @p_sitecode

    End

  • If siteglobalcode can be null then you may have to do something like this:

    Where...And Isnull(siteglobalcode,'') =

    Case 

        When @p_sitecode is null then Isnull(siteglobalcode, '')

        Else @p_sitecode

    End

    Of course the second Isnull parameter would have to be something that is an invalid siteglobalcode.

    Perhaps someone else can confirm.

     

  • You probably want to change def of proc to

    CREATE PROCEDURE missing_iconnt_data(@p_sitecode INTEGER = Null,@p_fromsalesdate DATETIME,@p_tosalesdate DATETIME)

    This means that if @p_sitecode is not specified it will take value Null

    Your WHERE then needs to become

    WHERE salesdate BETWEEN CONVERT(DATETIME, @p_fromsalesdate) and CONVERT(DATETIME, @p_tosalesdate)

    and siteglobalcode = IsNull(@p_sitecode,siteglobalcode)

    this means when @p_sitecode has a proper value it gets rows where siteglobalcode = that value otherwise it gets rows where siteglobalcode = siteglobalcode (i.e. any row where siteglobalcode is NOT null - I assume here that siteglobalcode always has a proper value)

  • I would change the order of the parameters like this:

    CREATE PROCEDURE missing_iconnt_data

    (

      @p_fromsalesdate datetime,

      @p_tosalesdate datetime,

      @p_sitecode int = NULL

    )

    That way, you can call the stored procedure this way:

    EXEC missing_iconnt_data @fromdate, @todate

    If @p_sitecode int = NULL comes first, then you must either include a value (although that value could be NULL), or used named parameters.

     

  • You might try this:
     
    WHERE   salesdate BETWEEN CONVERT(DATETIME, @p_fromsalesdate) and CONVERT(DATETIME, @p_tosalesdate)

                and (@p_sitecode is null or siteglobalcode = @p_sitecode)  

Viewing 5 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply