In this video you will learn how to use the SQL CASE statement to add “filter flexibility” to your front-end Excel worksheet, thus taking your SQL + Excel skills to the next level. I’ll reveal the UPDATED code I used to build a dynamic SQL statement using SQL Server and Excel.
By using Excel as a tool to pass cell values to SQL Server queries, you’ll be able to generate dynamic SQL statements on the fly, saving time and reducing the risk of errors in your code. Building upon the previous video “Call a SQL Server Stored Procedure using Excel Parameters”, let’s enhance your SQL skills and streamline your workflow.
Here is a screenshot of the front end Excel worksheet we setup in previous videos. This Excel sheet will execute a stored procedure call with parameters supplied from cells on the sheet.

Below is the stored procedure I use to enhance the code from previous videos. I setup a static SQL string that will serve as the base of the SQL statement. I then use the CASE statement to evaluate the cell values incoming from the Excel worksheet (with some slight manipulation for empty and default date values incoming from Excel).
Depending upon those values, the filter clause is dynamically built and appended to the base of the SQL string, which is then executed with the sp_executedqsl command. This command has many advantages with respect to protecting your code from a SQL injection attack.

If you need a breakdown of the code and the worksheet functionality, make sure to watch the video below.
Additional References to Maximize Your Learning
- Watch this previous video and/or refer to this blog post for worksheet details and for the quicker way to retrieve data.
- For maximum value on integrating Excel and SQL Server, make sure to watch this playlist creatively called: SQL Meets Excel: A Power Couple’s Guide to Data Retrieval .
- Refer to this video in order to learn the advantages of the sp_executesql command.
I always have fun creating this type of content and sharing with you, my YouTube channel followers.
Stay in contact with me through my various social media presences.
All views and opinions are solely my own and do not necessarily reflect those of my employer
I appreciate everyone who has supported this blog and my YouTube channel via merch. Please check out the logo shop here.
Thank you!!
Anthony B Smoak