Solved

Dynamic where clause

Posted on 2010-09-08
3
810 Views
Last Modified: 2012-05-10
Can someone show how to create a dynamic where clause in Sybase?

Eg.
I have a select statement with a where clause.

But  based on the count of rows returned from a table I want to add one more condition....
if the count is 0 then no additional condition needs to be added to the where clause
and if the count > 1, then I want to add the values returned by another select query  in the where clause  condition.

Thanks.
0
Comment
Question by:4Learning
3 Comments
 
LVL 14

Expert Comment

by:Jan_Franek
ID: 33634224
You can dynamicaly create your select command, store it into varchar variable and then execute it using dynamic exec - see http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.commands/html/commands/commands56.htm
0
 
LVL 2

Accepted Solution

by:
Rajesh_Anandappan earned 500 total points
ID: 33795793
example:

declare @sql_string varchar(255)
         ,@val varchar(10)

select @sql_string = 'select age from <table>'
      ,@val = 'joe'

IF exists (select 1 from <table>) -- if rows are there in this table
   BEGIN
      select @sql_string = @sql_string + ' where name = '+@val
      exec(@sql_string)
   END
ELSE
   BEGIN
      select 'No rows in table'
   END
0
 

Author Closing Comment

by:4Learning
ID: 33851616
Thankyou for the example. I tried the variable for the select clause, the from clause and the where clause and added them all up in one string and then passed that string as a parameter to the exec command as you listed above.

Thanks.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Hyena v12.2 is now available for downloading and is available in English, French, German and Spanish versions.
Is your company's data protection keeping pace with virtualization? Here are 7 dynamic ways to adapt to rapid breakthroughs in technology.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

743 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now