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 < 100
Generated select statement :
SELECT product_id, product_name, product_type, product_ price FROM products WHERE product_type = “widget” AND product_price < 100
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 < 100"; TSelectSqlStatement sql1, sql2; public string addsql() { TGSqlParser sqlparser = new TGSqlParser(TDbVendor.DbVMssql); TGSqlParser sqlparser2 = new TGSqlParser(TDbVendor.DbVMssql); sqlparser.SqlText.Text = sqlstr1; int ret = sqlparser.Parse(); if (ret != 0) return sqlparser.ErrorMessages; sql1 = sqlparser.SqlStatements[0] as TSelectSqlStatement; sqlparser2.SqlText.Text = sqlstr2; ret = sqlparser2.Parse(); if (ret != 0) return sqlparser2.ErrorMessages; sql2 = sqlparser2.SqlStatements[0] as TSelectSqlStatement; //get field name StringBuilder flds = new StringBuilder(); int p = 0; foreach (TLzField fd in sql1.Fields) { if (++p> 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