• Robin, Lasse, you guys need to leave the 90's and learn about sp_executesql.

    Charles, personally I think you're creating a nightmare for whoever comes after you. All the code being in strings means a mass of red coloured text in QA or Management studio. People might also quite easily try and guess the first param, see the a 0 returns *something* and think their query just returns no rows. There's also an added layer of gotcha's of making sure all your quotes are correctly double quoted, etc.

    I'm gonna put my hands up here in that I'm no expert on execution plans or the inner workings of SQL, but I think all those IF statements could cause the execution plan to be recreated a lot and cause extra overhead for SQL to check the truth of every IF statment.

    You're better off letting a proper programming language do the logic and letting SQL do what it does best, set based queries!