简体   繁体   中英

How to get column_name and table_name from DML statement?

I am building an algorithm to mock DB operations.

I have one problem, how i can get Table name and column names from a DML statement?

ie:

 string = "SELECT id,name FROM USER_TBL"
 string TABLE_NAME = getTableName(string); //this will return "USER_TBL"
 array COLUMN_NAME = getColumnNames(string); //this will return ["id","name"]

If i consider these as string manipulation, how i can design algorithm to get table name & column names?

Currently i use following logic,

function getTableName(iString){
   //find string between "FROM " to next " "(space) and return it 
}

function getColumnNames(string){
   //get string between "SELECT " and " FROM" and split string based on "," (comma) and return it
}

I wanted to know is there any algorithm already available for this(for reference)? What and all the cases i need to handle other than these?

I don't know an algorithm, but a few things that come to my mind: Table name - Tablenames can have aliases, but with your logic that should be OK - Can be prefixed with the database name (dbname.tblname) -> so you might need to look for dots before returning the string - Tablename can be a derived table --> select statement in brackets. In that case there is not really a simple to tablename derive

Column names - Column names can have aliases, not sure how you want to handle that. - What about calculations, conditions (Case when...) --> that is not just a column name but a combined or calculated value. In that case no real column name to retrieve - You can have also select statements for single columns in the resultset

So overall, your approach works if there is no complexity in the sql queries, if yes, your logic might not return what you want to.

What about other statements, like UPDATE and INSERT? Is that also something that you want to parse?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM