Skip to main content

Posts

Showing posts with the label What Does WHERE 1=1 Mean in the Code?

SQL SERVER – What Does WHERE 1=1 Mean in the Code?

One of the blog followers asked this question “The code written by my colleague has WHERE 1=1. What does it mean?” Well. You have seen people using it when they dynamically construct WHERE condition based on the input values. Let us create this dataset CREATE TABLE #t (emp_name VARCHAR(100), experience INT, specialist VARCHAR(100)) INSERT INTO #t SELECT 'Pinal',12,'SQL' UNION ALL SELECT 'John',10,'JAVA' UNION ALL SELECT 'Sudhan',3,'SQL' Suppose you want to use two parameters and pass values for them in such a way that if the value is null, you need to skip the comparison Check the following code DECLARE @experience INT, @specialist VARCHAR(100), @sql VARCHAR(100) SET @sql=' where 1=1' SET @sql = @sql+CASE WHEN @experience IS NULL THEN '' ELSE ' and experience='''+CAST(@experience AS VARCHAR(100))+'''' END SET @sql = @sql+CASE WHEN @specialist IS NULL THEN '' ELSE ...