Dynamic Where Query in SQL Server

Hello everyone,

In this article, I will give information about the use of dynamic where query in SQL Server.

In SQL Server, in some cases, you may want to use two or more where conditions dynamically.

I created the following code based on the Northwind database. You can use it according to your own database or according to the Northwind database.

DECLARE @WhereSentence1 NVARCHAR(MAX),
        @WhereSentence2 NVARCHAR(MAX);
SELECT @WhereSentence1 = N' AND TitleOfCourtesy=''Ms.''',
       @WhereSentence2 = N' AND City = ''London''';
DECLARE @SQLSentence NVARCHAR(MAX);
SELECT @SQLSentence = N'SELECT * FROM Employees WHERE EmployeeID=9 ' + @WhereSentence1 + @WhereSentence2;
PRINT @SQLSentence;
EXEC sys.sp_executesql @SQLSentence;

When you run the code, you will get a result like the one below.

Dynamic Where Query in SQL Server

As you can see, we have used two where clauses dynamically.

Good luck to everyone in business and life.

265 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!