[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

dynamic sql filter in T-SQL

Posted on 2014-08-02
3
Medium Priority
?
136 Views
Last Modified: 2014-08-02
I have a ton of stored proc code that I would like to prevent duplication if possible and one parameter which
if null would require a filter to be changed and thus a rewrite of code. What I would like to do is parameterize the filter string...
 So instead of this:
 
if @pCol is not null
begin
     Select * from my_tab where col = @pCol;
end
else
begin
   select * from my_tab where col is not null;
end 

Open in new window


Is there a way to do this dynamically
something like so:
declare col_filter varchar(50);

if @pCol is null
begin
set col_filter = ' col is not null';
end
else
begin
set col_filter = ' col = @pCol';
end

select * from my_table where || @filter_col ;

Open in new window


Thanks!
0
Comment
Question by:Focker513
3 Comments
 
LVL 21

Assisted Solution

by:Randy Poole
Randy Poole earned 1000 total points
ID: 40236556
Why not
Select * from my_tab where ((pcol = @pCol and @pcol is not null) or (col is not null and @pcol is null))

Open in new window

0
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 1000 total points
ID: 40236562
this will do, without dynamic sql:
Select * from my_tab where ( col = @pCol or  @pCol  is null) ;
0
 

Author Closing Comment

by:Focker513
ID: 40236565
Thanks gentlemen, I appreciate it!
0

Featured Post

Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question