Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8520789
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T06:37:46+00:00 2026-06-11T06:37:46+00:00

I have several tables. I have a query also. My problem is to generate

  • 0

I have several tables. I have a query also. My problem is to generate the SQL query dynamically using Java.

I have the following fields in a separate table:

 Collumn name          status
po_number,               Y
unit_cost,               Y
placed_date ,            Y
date_closed,             Y
scheduled_arrival_date   Y
date_closed              Y 
order_quantity           Y
roll_number              N
product_sku              N
product_category_name    N
rec_vendor_quantity      Y  
vendor_name              Y
et_conversion_unit_quantity Y

from which i have to generate a query when the status is Y, the problem here is some time the above columns

The following query is the out put of the above :

here i have inculded all the columns but i have to exculde the column which has the status of N, please help me to construt the query using java.

select
pi.po_number,poi.unit_cost,pi.placed_date CreateDate,
case when isnull(pi.date_closed) then pi.scheduled_arrival_date  
else pi.date_closed end as ReceviedDate,
poi.order_quantity,poi.roll_number,p.product_sku product_name,
pc.product_category_name,poi.rec_vendor_quantity,pv.vendor_name,p.et_conversion_unit_quantity,pi.note
from
purchase_order as pi,
purchase_order_inventory as poi,
product_vendors as pv,
products AS p,
product_categories AS pc
where
pi.purchase_order_id=poi.purchase_order_id and
pc.product_category_id=p.product_category_id and
poi.product_id = p.product_id and
poi.product_category_id=pc.product_category_id and
pi.vendor_id=pv.product_vendor_id and
( ( pi.date_closed  >= '2012-01-01' and pi.date_closed <='2012-09-05 23:59:59' ) 
or ( pi.scheduled_arrival_date  >= '2012-01-01' and pi.scheduled_arrival_date <='2012-09-05 23:59:59') ) and
pi.po_type=0 
and pi.status_id = 0 and  poi.transaction_type = 0  
order by pi.po_number 

UPDATE :

QUERY : STEP 1:

SELECT rcm.id,rcm.tablename,rcm.columnname,rcm.size,rcm.displayorder,rcm.isactive FROM report_customise_master rcm where rcm.tablename !='employee' and rcm.isactive='Y' order by rcm.displayorder;

STEP 2 :
Java method to construct the query :

public Map getComplexReportQuery() {
    String query = "SELECT rcm.id,rcm.tablename,rcm.columnname,rcm.size,rcm.displayorder,rcm.isactive FROM report_customise_master rcm where rcm.tablename !='employee' and rcm.isactive='Y' order by rcm.displayorder;";
    String tableName = "", from = "", select = "";
    StringBuffer sb = new StringBuffer();
    Map<String, List<String>> resultsMap = new LinkedHashMap<String, List<String>>();
    Map<String, String> displayOrderMap = new LinkedHashMap<String, String>();
    Map queryMap = new LinkedHashMap();
    if (!query.isEmpty() || query.length() > 0) {
        sb.append(query);
    }

    Connection connection = getConnection();
    if (connection != null) {
        try {
            PreparedStatement reportQueryPS = connection.prepareStatement(sb.toString());
            ResultSet reportQuery_rst = reportQueryPS.executeQuery();
            List<String> tables = new ArrayList<String>();;
            if (reportQuery_rst != null) {
                StringBuilder selectQuery = new StringBuilder(" SELECT ");
                StringBuilder fromQuery = new StringBuilder(" FROM ");
                while (reportQuery_rst.next()) {
                    tableName = reportQuery_rst.getString("tablename");
                    List<String> columns = resultsMap.get(tableName);
                    if (columns == null) {
                        columns = new ArrayList<String>();
                        resultsMap.put(tableName, columns);
                    }
                    columns = resultsMap.get(tableName);
                    String columnName = reportQuery_rst.getString("columnname");

                    columns.add(columnName);
                }
                tableName = "";
                for (Entry<String, List<String>> resultEntry : resultsMap.entrySet()) {
                    tableName = resultEntry.getKey();
                    List<String> columns = resultEntry.getValue();
                    int i = 0;
                    for (String column : columns) {
                        selectQuery.append(tableName + "." + column);
                        if (i != columns.size()) {
                            selectQuery.append(",");
                        } else {
                            selectQuery.append("");
                        }
                        i++;
                    }
                    if (!tables.contains(tableName)) {
                        tables.add(tableName);
                    }
                }
                //to remove comma at the end of line
                select = selectQuery.toString().replaceAll(",$", "");
                tableName = "";
                int i = 0;
                for (String table : tables) {
                    fromQuery.append(table);
                    fromQuery.append(" ");
                    fromQuery.append(table);
                    if (i != tables.size()) {
                        fromQuery.append(",");
                    } else {
                        fromQuery.append("");
                    }
                    i++;
                }
                from = fromQuery.toString().replaceAll(",$", "");
                queryMap.put("query", select + from);
            }
            //from = from+"ORDER BY "+orderbyColumn+" "+sort+" ";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                closeConnection(connection, null, null);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    } else {
        System.out.println("Connection not Established. Please Contact Vendor");
    }
    return queryMap;// return the map/ list which  contains query and sory and display order
}    

STEP 3 : Result query
{query= SELECT purchase_order.po_number,purchase_order.placed_date,purchase_order.date_closed,purchase_order.scheduled_arrival_date,purchase_order_inventory.unit_cost,purchase_order_inventory.order_quantity,purchase_order_inventory.roll_number,purchase_order_inventory.rec_vendor_quantity,products.product_sku,products.et_conversion_unit_quantity,product_categories.product_category_name ,product_vendors.vendor_name FROM purchase_order purchase_order,purchase_order_inventory purchase_order_inventory,products products,product_categories product_categories,product_vendors product_vendors}

but this not what i wanted, Please help me to construct the query i have given.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T06:37:48+00:00Added an answer on June 11, 2026 at 6:37 am

    Two queries

    You need to make two queries:

    1. Query which fields are enabled
    2. Build the second query string (the one you want to build dinamically)

    It’s this way because a SQL query has to tell which columns will be included before querying any data. In fact it will be used to build the internal DB query plan, it is, the way the DB motor will use to retrieve and organize the data you ask.

    Query all columns

    Is it necesary to query only that fields? Can’t you query everything and use the relevant data?

    Joins

    Looking at the updated question I guess you need to dynamically add where conditions to join tables correctly. What I should do is have a reference telling me what coindition to add when a table is present.

    There are at least two options:

    1. Based on table pairs present (by example: “if A and B are present then add A.col1 = B.col2”)
    2. Based on tables present (“if B is present, then add A.col1 = B.col2; A should be present”

    Based on your example I think the second option is more suitable (and easy to implement).

    So I should have some static Map<String, JoinInfo> where JoinInfo has at least:

    JoinInfo
    + conditionToAdd // by example "A.col1 = B.col2"
    + dependsOnTable // by example "A" to indicate that A must be present when B is present
    

    So you can use:

    1. that info to add tables that should be (by example: even if A has no selected cols, must be present to join with B)
    2. include the conditionToAdd to the where clause

    Anyway… I think you are getting into much trouble. Why so dynamic?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have several tables, books, bookcategories, categories bookcategories is a join table to allow
I have several tables: CREATE TABLE [dbo].[Tracks]( [Id] [uniqueidentifier] NOT NULL, [Artist_Id] [uniqueidentifier] NOT
We are using SQL Server 2008. We have a table called response which has
I have several TEXT and/or MEDIUMTEXT fields in each of our 1000 MySQL tables.
I have a query that creates several temporary tables and then inserts data into
I have a SQL query that retrieves data from a table that lists athletes'
I have a query that returns a datetime field and several other fields along
I have a class hierarchy that I want to map across several tables using
I have the following problem: We have several different databases on which our program
I have the following 2 tables: ProductCombined - several product informations are stored here

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.