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.
As you can see, we have used two where clauses dynamically.
Good luck to everyone in business and life.