We have some logging service from an API that's having some trouble catching the database a query is accessing.
Say, a query comes like this:
Select Top 10 * From DataBase..Table
What I'd like to achieve is to get "DataBase" or the text prior to the ".." on the string.
Also, sometimes a query comes like this:
Select Top 10 * From DataBase.Schema.Table
Is it possible to get the "DataBase" string on both cases?
Here's what I've been trying to do, but I not that good in regular expressions.
([A-Z]+\.+?([A-Z])*(\.)+[A-Z])
But this matches the following (on square brackets):
Select Top 10 * From [DataBase..T]able
Thanks for the help!
Edit: This is done in C#, prior to sending the query/request to the database, we are trying to log every request this API method processes.
As it is mentioned in comment, parsing SQL this way is a bad idea due complexities that you can encounter. But if this is something you want to do, following should work. It will work for select or delete statements, insert/update won't work as they have different structure.
public string GetDbName(string sql)
{
var sqlLower = sql.ToLower();
var parts = sqlLower.Split(new string[] { "from " }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
{
//something is wrong in sql;
//may be its not a select statement
return null;
}
var tableName = parts[1]
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault();
var posOfTableName = tableName.LastIndexOf('.');
var dbName = tableName.Substring(0, posOfTableName);
//We can return here, but it will return lower case db name parts
//We can also get the original value as well by looking into original parameter
var indexOfStart = sqlLower.IndexOf(dbName);
return sql.Substring(indexOfStart, dbName.Length);
}
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.