Skip to content
No results
We use cookies to ensure that we give you the best experience on our website.

# Analyze 2 select statements, then merge into one statement

This demo illustrates how to get columns from select list and tables in from clause of 2 select statements, and then create a new select statement based on these columns and tables information.

Input select statement 1:

    SELECT product_id, product_name, product_type
    FROM products
    WHERE product_type = "widget"

Input select statement 2:

    SELECT product_id, product_name, product_ price
    FROM products
    WHERE product_price
    Generated select statement :

    SELECT product_id, product_name, product_type, product_ price
    FROM products
    WHERE product_type = “widget” AND product_price
    Code to process select statement in C#

    using System;
    using System.Collections.Generic;
    using System.Text;
    using gudusoft.gsqlparser;
    using gudusoft.gsqlparser.Units;

    namespace buildsql
    {

        class add2sqls
        {
            string sqlstr1 = @"SELECT product_id, product_name, product_type FROM products WHERE product_type = “widget”"
                , sqlstr2 = @"SELECT product_id, product_name, product_ price FROM products WHERE product_price  1) flds.Append(",");
                    flds.Append(fd.AsText);
                }

                foreach (TLzField fd in sql2.Fields)
                {
                    if(flds.ToString().IndexOf(fd.AsText) == -1)
                    flds.Append(","+fd.AsText);
                }

                //get tablename name
                StringBuilder tlbs = new StringBuilder();
                p = 0;
                foreach (TLzTable tl in sql1.Tables)
                {

                    if (++p > 1) tlbs.Append(",");
                    tlbs.Append(tl.AsText);
                }

                foreach (TLzTable tl in sql2.Tables)
                {
                    if (tlbs.ToString().IndexOf(tl.AsText) == -1)
                        tlbs.Append("," + tl.AsText);
                }

                // Console.WriteLine("sb: "+sb.ToString());
                // get fields list from sql1

                String wherestr = "";
                if (sql1.WhereClause != null)
                {
                    wherestr = sql1.WhereClauseText;
                }

                if (sql2.WhereClause != null)
                {
                    wherestr = wherestr+" and "+sql2.WhereClauseText;
                }

                return "select " + flds.ToString() + " from " + tlbs.ToString() + " where "+wherestr;
            }
        }
    }

    Download this demo: C# version, Java version