How to get columns and tables used in SQL statement

I need to get the columns and tables used in the query, but I do not find an elegant way to do this. I am looking for this, but cannot find information that works for me. The request has this format

select TABLE1.Id, TABLE2.Name, TABLE3.Observations, TABLE3.Adress, --and more 70 fields
from TABLE1, TABLE2, TABLE3, TABLE4

Is there a good way to accomplish these two tasks?

+4
source share
2 answers

, SqlCommand.Parameters SqlParameter, . . SqlCommand SQL Safe . :

SqlCommand sql = new SqlCommand("SELECT TABLE1.Id, TABLE2.Name, TABLE3.Observations, TABLE3.Address FROM TABLE1, TABLE2, TABLE3, TABLE4 WHERE TABLE2.Name = @Name")
sql.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 32));
sql.Parameters["@Name"] = "Your Name";

SQL @Name SQL Safe 'Your Name'.

, , . .

( ) , SELECT FROM , , .

, , ( ):

// sql.CommandText can be replaced with the raw SQL Query String
string query = sql.CommandText;
string removeSelect = query.Substring(7); // Remove the SELECT and space
string removeAfterFrom = removeSelect.Substring(0, removeSelect.IndexOf(" FROM ")); // Remove the FROM
string[] columns = removeAfterFrom.Split(','); // Get each Column

List<string> tables = new List<string>();

for (int i = 0; i < columns.Length; i++)
{
    string[] columnName = columns[i].Split('.');
    if (columnName.Length > 1)
        if (!tables.Contains(columnName[0]))
            tables.Add(columnName[0].Trim());
}

, , FROM.

, - SQL Parser, / SQL-. SELECT, all, , (*) , TOP (n). TOP (n), . , . (I.e. : SELECT TABLE1.Name FROM TABLE1 SELECT Name FROM TABLE1.

all, ( , ), .

// sql.CommandText can be replaced with the raw SQL Query String
string query = sql.CommandText;
string removeSelect = query.Substring(7); // Remove the SELECT and space
string[] splitOnFrom = removeSelect.Split(new string[] { " FROM " }, StringSplitOptions.RemoveEmptyEntries);
string[] columns = splitOnFrom[0].Split(','); // Get each Column
string[] tables = splitOnFrom[1].Split(','); // Get each Table

columns , tables .

: FROM () . FROM, FROM . FROM , :

string removeAfterFrom = removeSelect.Substring(0, removeSelect.IndexOf(" FROM ", StringComparison.CurrentCultureIgnoreCase));

, .


, , . ( , Google , .)

+2

.

SQL (, begin tran/rollback tran), SqlDataReader.

-, . , select a.b, c, d.e from ....

+1

All Articles