I am trying to parse a SQL query using:
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo);
DataTable schemaTable = reader.GetSchemaTable();
I get base table names, but I also need to find the table alias names.
Example Query:
select AuthorId, a.Name as [AuthorName], c.Name as City, s.Name as [State] from Author a
inner join Zipcode zc on zc.ZipCodeId = a.ZipCodeId
inner join City c on c.CityId = zc.CityId
inner join [State] s on s.StateId = c.StateId
I have checked regex solution, but not able to figure out how to extract "Author a", "ZipCode cd", "City c", "[State] s"
Definitions that you must take into account to work with Regex type syntax.
Metacharacters
Metacharacters specify characters users can enter at the corresponding positions.
.
[aeiou]
[^aeiou]
[0-9a-fA-F]
\w
[a-zA-Z_0-9]
\W
[^a-zA-Z_0-9]
\d
[0-9]
\D
[^0-9]
Quantifiers
Quantifiers follow a metacharacter and specify how many times the character should be repeated. The table below lists the available qualifiers.
*
{0,}
[a-zA-Z]
,\w
+
{1,}
[a-zA-Z]+
,\w+
?
{0,1}
[a-zA-Z]?
,\w?
{n}
[0-9]{2}
{n,}
[0-9]{2,}
{n,m}
[0-9]{2,7}
Solutions that can be of help.
1. Extract table names from an SQL statement with Regex
Regular expression
2. Extract table names with alias from an SQL statement with Regex
Regular expression
3. Extract column names from an SQL statement with Regex
Regular expression
Generated Code for C#
Test string
Output
More code sample for C# (Here)
https://stackoverflow.com/a/68889908/16731336
References
Extract table names from an SQL statement with Regex
Regular Expression Language - Quick Reference
Simplified Regular Expressions