Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Dynamic where clause

Posted on 2010-09-08
3
813 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Starting your own business is always a daunting process, and for most people it is brand new experience. Avoid the common pitfalls by following these tips to start on the road to success.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

839 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