Creating a Dynamic Where Clause in a stored procedure in SQL Server

I want a stored procedure in SQL Server to have two optional parameters, @CUSTOMERID and @ASSEMBLYID, and return a recordset.  The procedure will only ever be called with just one of the two parameters specified.  If the first one is specified I want the WHERE cause of the recordset to be "WHERE CustomerId = @CUSTOMERID", and if the second parameter is specified I want the WHERE clause to be "WHERE AssemblyId = @ASSEMBLYID".  How can I dynamically create the where clause based on which parameter is provided?  Can I save the SQL to a string variable and then somehow execute the string variable to generate and return the recordset?
LVL 1
Declan_BasileITAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Arun MuruganCommented:
You don't need a dynamic SQL for this. You can do this simply with WHERE clause.
CREATE PROCEDURE MY_PROC
(
	@CUSTOMERID INT = NULL,
	@ASSEMBLYID INT = NULL
)
AS
BEGIN
	SELECT
	*
	FROM
	   tbl_MyTable
	WHERE
	   CustomerId = @CUSTOMERID
	   OR
	   AssemblyId = @ASSEMBLYID
END
GO

Open in new window

If you pass @CUSTOMERID then it will just execute the first condition and will not proceed to other part of the OR.
If you pass @ASSEMBLYID, the first part of the OR will fail and it will proceed to the other part.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Najam UddinCommented:
where (
             (CustomerId = @CUSTOMERID OR @CUSTOMERID IS NULL)
           OR 
            (ASSEMBLYID = @ASSEMBLYID OR @ASSEMBLYID IS NULL)
           )

Open in new window


However this kind of approach does not generate efficient query plan for both conditions, better split in two queries.

@Arun Murugan - Your query will give wrong results
Scott PletcherSenior DBACommented:
Because of the parameter changes, for efficiency you'll want SQL to recompile the query every time:

      SELECT
          *
      FROM
          tbl_MyTable
      WHERE
         CustomerId = @CUSTOMERID
         OR
         AssemblyId = @ASSEMBLYID
      OPTION (RECOMPILE)
Protecting & Securing Your Critical Data

Considering 93 percent of companies file for bankruptcy within 12 months of a disaster that blocked access to their data for 10 days or more, planning for the worst is just smart business. Learn how Acronis Backup integrates security at every stage

Arun MuruganCommented:
@Najam - Just wanted to know Why? What is the difference you found between the WHERE clauses you and I have posted?
Najam UddinCommented:
For any customerid other than @CUSTOMERID where AssemblyId  is null , that will be part of your result, which is not correct also other way around for AssemblyId
Najam UddinCommented:
where (
             (CustomerId = @CUSTOMERID OR @CUSTOMERID IS NULL)
           AND 
            (ASSEMBLYID = @ASSEMBLYID OR @ASSEMBLYID IS NULL)
           )

Open in new window


will be the good one
Arun MuruganCommented:
Requirement doesn't state that. Let the author decide.
Scott PletcherSenior DBACommented:
@Najam:

That is not true.  A NULL value is never "=" another value, even another NULL.  The first syntax is fine and much cleaner.

      WHERE
         CustomerId = @CUSTOMERID --a NULL CustomerID will NOT "=" a NULL @CUSTOMERID
         OR
         AssemblyId = @ASSEMBLYID --a NULL AssemblyId will NOT "=" a NULL @ASSEMBLYID

As noted, it could have performance issues being in the same proc, and therefore I stated that a recompile option ("hint") was also needed:

      WHERE
         CustomerId = @CUSTOMERID
         OR
         AssemblyId = @ASSEMBLYID
       OPTION (RECOMPILE)
Najam UddinCommented:
@ScottPletcher & @Arun Murugan - I agree, my bad.
Declan_BasileITAuthor Commented:
What do you think about this solution?  Would I need an OPTION (RECOMPILE) if I did it this way?

DECLARE @SQL varchar(1000) 

SET @SQL = 'SELECT *.Assemblies FROM Assemblies WHERE ' 
IF @CUSOMTERID IS NOT NULL 
     SET @SQL = @SQL + 'CUSTOMERID = @CUSTOMERID '
ELSE
     SET @SQL = @SQL + 'ASSEMBLYID = @ASSEMBLYID '
END
    
EXEC(@SQL)

Open in new window

Scott PletcherSenior DBACommented:
No.  And if you have more than two or three options, that is the preferred way to do it.  Except you must also deal with potential SQL injection, such as by using sp_executesql and providing the value of @CUSTOMER|@ASSEMBLYID only as parameter values, not strung directly into the query as any kind of text.
Declan_BasileITAuthor Commented:
Thanks you.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.