Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1736
  • Last Modified:

Help SQL SP If Null Statement

Could someone please advise why this sql sp receives this error "Msg 156, Level 15, State 1, Procedure qry_Invoice_To_Run, Line 22
Incorrect syntax near the keyword 'HAVING'."
I'm having trouble with the if is null code at the end.

Thank you.

ALTER PROCEDURE [dbo].[qry_Invoice_To_Run]
       @startdate datetime,                  -->[forms]![frminvoicecreator]![startdate]
       @enddate datetime,                        -->[forms]![frmInvoiceCreator]![enddate]
       @clientnumber int =  null,
       @subnumber int = null
AS
BEGIN
      SET NOCOUNT ON
set identity_insert tbx_invoice_run on
INSERT INTO tbx_Invoice_run ( ID, [CLIENT NUMBER], SubNumber, OrganizationName )
SELECT     CLIENTS.ID, CLIENTS.[CLIENT NUMBER], CLIENTS.SubNumber, CLIENTS.OrganizationName
FROM         CLIENTS INNER JOIN
                      MATTERS ON CLIENTS.SubNumber = MATTERS.SubNumber AND CLIENTS.[CLIENT NUMBER] = MATTERS.[CLIENT NUMBER]
WHERE     (MATTERS.[Actual Closing Date] BETWEEN @startdate AND @enddate)
GROUP BY CLIENTS.ID, CLIENTS.[CLIENT NUMBER], CLIENTS.SubNumber, CLIENTS.OrganizationName
If (@clientnumber) = null
      HAVING (CLIENTS.[CLIENT NUMBER]  <> 888
else
      HAVING (CLIENTS.[CLIENT NUMBER]  = @clientnumber and clients.subnumber = @subnumber)
end
ORDER BY CLIENTS.[CLIENT NUMBER], CLIENTS.SubNumberset identity_insert tbx_invoice_run off
0
dleads
Asked:
dleads
1 Solution
 
MikeWalshCommented:
I am fairly certain that you can't put an IF statement into you where clause like that. If you need to have a conditional having clause like that you will need to use dynamic sql or take care of the variable assignment before you get into the select.
0
 
MikeTooleCommented:
The HAVING clause is only needed when testing the result of an expression in the GROUP BY.
Put all the selection in the Where clause as in the attached snippet
WHERE (MATTERS.[Actual Closing Date] BETWEEN @startdate AND @enddate)
AND  (
      ((@clientnumber is null) AND (CLIENTS.[CLIENT NUMBER]  <> 888)) OR
      ((CLIENTS.[CLIENT NUMBER]  = @clientnumber) AND (clients.subnumber = @subnumber))
     )

Open in new window

0

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Tackle projects and never again get stuck behind a technical roadblock.
Join Now