Wednesday, August 18, 2010

Alternate to Dynamic Sql in Sql Server

Following in the Example having an alternate to Dynamic Sql in Sql Server
----------------------------------
create table testtable

( col1 int, col2 int)

insert into testtable(col1, col2)
Values
(10,20),
(30,40),
(11, 15),
(17, 16)
----------------------
Show 1
-----------------------
Declare @col1 int
Declare @col2 int

Set @col1 = 15
SET @col2 = null

Select * from testtable
Where (col1 > @col1 OR @col1 IS NULL)
AND (col2 > @col2 OR @col2 IS NULL)

--------------------------------
Show 2
--------------
Declare @col11 int
Declare @col12 int

SET @col11 = 10
set @col12 = 30
Select * from testtable
Where (col1 = @col11 OR @col11 IS NULL)
or (col1 = @col12 OR @col12 IS NULL)
---------------------------------
Drop table testtable
------------------------

Also you can check the following article from the code project by John P Harris, which have different ways of avoiding Dynamic Sql such as

* Using COALESCE
* Using ISNULL
* Using CASE
* Alternative

Implementing Dynamic WHERE-Clause in Static SQL

No comments: