-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathreplaceTablename.java
More file actions
65 lines (54 loc) · 2.19 KB
/
Copy pathreplaceTablename.java
File metadata and controls
65 lines (54 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package gudusoft.gsqlparser.demos.modifysql;
import gudusoft.gsqlparser.EDbVendor;
import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.nodes.TTable;
import gudusoft.gsqlparser.stmt.TSelectSqlStatement;
import gudusoft.gsqlparser.TSourceToken;
/**
* This demo shows how to replace a specified table name with new one.
* <p>Steps to modify a table name:
* <p>1. find the table name that need to be replaced.
* <p>2. use setString method to set a new string representation of that table.
*
* <p>In this demo, input sql is:
*
* <p>select table1.col1, table2.col2
* <p>from table1, table2
* <p>where table1.foo > table2.foo
*
* <p>we want to replace table2 with "(tableX join tableY using (id)) as table3"
* <p>and change table2.col2 to table3.col2, table2.foo to table3.foo accordingly.
*
*/
public class replaceTablename{
public static void main(String args[])
{
TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvoracle);
sqlparser.sqltext = "select table1.col1, table2.col2\n" +
"from table1, table2\n" +
"where table1.foo > table2.foo";
System.out.println("input sql:");
System.out.println(sqlparser.sqltext);
int ret = sqlparser.parse();
if (ret == 0){
TSelectSqlStatement select = (TSelectSqlStatement)sqlparser.sqlstatements.get(0);
TTable t ;
for(int i=0;i<select.tables.size();i++){
t = select.tables.getTable(i);
if (t.toString().compareToIgnoreCase("table2") == 0){
for(int j=0;j<t.getLinkedColumns().size();j++){
if(t.getLinkedColumns().getObjectName(j).getObjectToken().toString().equalsIgnoreCase("table2")){
TSourceToken token = t.getLinkedColumns().getObjectName(j).getObjectToken();
token.setAstext("table3");
}
}
t.setString("(tableX join tableY using (id)) as table3");
}
}
System.out.println("\noutput sql:");
System.out.println(select.toString());
}else{
System.out.println(sqlparser.getErrormessage());
}
}
}