This question already has answers here:
Retrieve List of Tables from Specific Database on Server C#
(7 answers)
Closed 7 years ago.
How can I make a code to get the number of tables to a link textbox in a given database? I'm using visual studio 2013 and I'm new to this. I used database server ms sql.
public static List<string> GetTables(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
DataTable schema = connection.GetSchema("Tables");
List<string> TableNames = new List<string>();
foreach (DataRow row in schema.Rows)
{
TableNames.Add(row[0].ToString());
}
return TableNames;
}
}
To be honest, i don't understand the question. You want the count of tables in a given database. The database is specified by the connection-string. You have already the code that returns a DataTable with all tables.
So here is the missing piece. Since connection.GetSchema("Tables") also returns views, if you want to count both you are ready with:
DataTable schema = connection.GetSchema("Tables");
int tableAndViewCount = schema.Rows.Count;
If you only want to count tables and exclude views:
int tableCount = schema.AsEnumerable().Count(t => t.Field<string>("TABLE_TYPE") == "BASE TABLE");
Get count of tables using the below query , just add that query in your application.
SELECT COUNT(*) from information_schema.tables
WHERE table_type = 'base table'
Try this Query
select * from sys.tables
Related
This question already has answers here:
How to run multiple SQL commands in a single SQL connection?
(9 answers)
How do I return multiple result sets with SqlCommand?
(7 answers)
Closed 5 years ago.
I'm having trouble to figure out how to get more then one SQL query to work in C#. I have something like this:
breakControlq.CommandText =
#"SELECT something as q1 From table" +
"SELECT somethingelse as q2 FROM table where this = this";
breakControlq.CommandType = CommandType.Text;
breakControlq.Connection = hd01Connect;
try
{
hd01Connect.Open();
breakControlRead = breakControlq.ExecuteReader();
while (breakControlRead.Read())
{
textBox1.AppendText(breakControlRead["q1"].ToString());
textBox2.AppendText(breakControlRead["q2"].ToString());
}
catch(System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message, "Connection Error");
}
Is this possible to do?
Do I have to repeat the connection/command to every single query?
I'm pretty new at this and some of you will tell that this has already been answered somewhere, but I searched so many posts that I'm more confused then when a started to search for the solution.
You are looking for .NextResult(). The .Read() method changes to the next row in the current grid; .NextResult() moves to the next grid:
while (breakControlRead.Read())
{
// process rows from first grid
}
if(breakControlRead.NextResult()) {
while (breakControlRead.Read())
{
// process rows from second grid
}
}
Alternatively; "dapper" would expose this via .QueryMultiple():
using(var multi = conn.QueryMultiple(sql, args)) {
var s = multi.Read<string>().AsList(); // items from first grid
var i = multi.ReadSingle<int>(); // items from second grid
// ...
}
Note! You do need to ensure that your two queries are separated by either whitespace or ;; in your case this would be fine:
#"SELECT something as q1 From table
SELECT somethingelse as q2 FROM table where this = this";
(note whitespace)
alternative and more correctly:
#"SELECT something as q1 From table;
SELECT somethingelse as q2 FROM table where this = this;";
or:
#"SELECT something as q1 From table;SELECT somethingelse as q2 FROM table where this = this;";
I'm having trouble to figure out how to get more then one SQL query to
work in C#
Well, wrap both your SQL statement in a stored procedure and call that procedure from your application code like
create procedure usp_data
as
begin
SELECT something as q1 From table;
SELECT somethingelse as q2 FROM table where this = this;
end
See How to: Execute a Stored Procedure that Returns Rows for more information
How can I get index names for an Access table using OLEDB or SQL ?
(I searched a lot on the internet in the last two days and did not find anything related to this issue.)
The OleDbConnection has a method called GetSchema that takes a string to select the collection of metadata that you want to retrieve.
Some of the possible values for the string parameter are Tables, Columns, Indexes
using(OleDbConnection cnn = new OleDbConnection("...."))
{
cnn.Open();
DataTable schemaIndexes = cnn.GetSchema("Indexes");
foreach(DataRow row in schemaIndexes.Rows)
{
Console.WriteLine("Table={0}, Index={1} on field={2}",
row.Field<string>("TABLE_NAME"),
row.Field<string>("INDEX_NAME"),
row.Field<string>("COLUMN_NAME"));
}
}
This question already has answers here:
List of tables used in an SQL Query
(5 answers)
Closed 9 years ago.
I need extract from simple string that represent an sql query the tables that are used on the query without execute the query itself in C#.
Example:
string strQuery = "SELECT * FROM table1 LEFT JOIN (SELECT * FROM table2) tt WHERE tt.name IN (SELECT name FROM table3)";
ArrayList arrUsedTables = GetUsedTablesFromQuery(strQuery);
and after this line the object arrUsedTables would contain:
table1,table2,table3
Remember that the query may be much complicated!
Without going to the DB you can't know for certain the names of the tables used in the query.
What if your query uses a view or a stored procedure?
Without consulting the database, these are transparent to the consumer.
The only way to be certain is to query the list of the tables from the database and then to attempt to parse them from your inline sql.
You will have to add references and directives for the following assemblies:
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
using System.IO;
Then, you may create the GetUsedTablesFromQuery method:
private static ArrayList GetUsedTablesFromQuery(string strQuery)
{
var parser = new TSql100Parser(true);
IList<ParseError> errors = new List<ParseError>();
using (TextReader r = new StringReader(strQuery))
{
var result = parser.GetTokenStream(r, out errors);
var tables = result
.Select((i, index) => (i.TokenType == TSqlTokenType.From) ? result[index + 2].Text : null)
.Where(i => i != null)
.ToArray();
return new ArrayList(tables);
}
}
You can certainly use a SQL parser such as ANTLR, as described in this question and answer, in order to get a full parse of the SQL, and then extract the table names.
Another option is to execute some raw SQL to get the execution plan of the query (using the instructions here). The execution plan is in XML, and then you can use Linq to XML to query the plan for all Table attributes on any ColumnReference tag.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get the generated SQL-Statement from a SqlCommand-Object?
I would like to know how to retrieve the SQL query that was executed by a Table Adapter for logging purposes.
For example:
Input:
RandomTableAdapter tableAdapter = new RandomTableAdapter();
tableAdapter.Insert("val","val","val","val");
Output:
What I would like to log is the insert statement, which is generated by the table adapter in order to execute the insert command.
Insert INTO RandomTable VALUES ('val', 'val', 'val', 'val');
How can I do this? Does anyone have any suggestions regarding this?
You can use this workaround with replace ParameterName with its value
but it not good because you need to manage value formatting by your own, and it can be slow
and you will need to get parameters after Insert is executed
code:
var usersTableAdapter = new testDataSetTableAdapters.usersTableAdapter();
usersTableAdapter.Insert(4, "home", "origin", "email#host.com", "realname", "spec", 1, "username", "usernick", "whereform");
var cmd = usersTableAdapter.Adapter.InsertCommand;
var text = cmd.CommandText;
var sb = new StringBuilder(text);
foreach (SqlParameter cmdParam in cmd.Parameters)
{
if (cmdParam.Value is string)
sb.Replace(cmdParam.ParameterName, string.Format("'{0}'", cmdParam.Value));
else
sb.Replace(cmdParam.ParameterName, cmdParam.Value.ToString());
}
Console.WriteLine(sb.ToString());
I have an SQL query I get from a configuration file, this query usually contains 3-6 joins.
I need to find at run time, based on the result set represented by SqlDataReader, to find the name of the table for each column.
Here are some thing that don't work:
SqlDataReader.GetName returns the column name but not the table name.
SqlDataReader.GetSchemaTable returns a data table with column information - but all the table names are null.
Querying information_schema doesn't help because I need data on the results of the current query (and the column names are not unique - there are columns with the same name in different tables).
I'm using .net 3.5SP1/ C#/ SQL Server 2008 in a console application.
EDIT: I know this is not possible for all cases since a "column" can be combined from multiple tables, a function or even a constant expression - I'm looking for something that works in the simple case.
EDIT 2: Found out why it didn't work - You can use SqlDataReader.GetSchemaTable to get table information but you have to set CommandBehavior to KeyInfo, you do that in the ExecuteReader call:
reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
You can use SqlDataReader.GetSchemaTable to get table information but you have to set CommandBehavior to KeyInfo, you do that in the ExecuteReader call:
reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
This unanswered question on stackoverflow uses SqlDataReader.GetSchemaTable to get the table name. Their problem is that it returns the actual table name rather than the alias that the table has. Not sure if this works with your sql but figured I'd let you know just in case.
I don't know if this information is available. In particular, not all columns of a result set come from a table. From a relational point of view, tables and resultsets are the same thing.
reader = cmd.ExecuteReader();
reader.GetSchemaTable().Rows[0]["BaseTableName"];
In general, this is not possible. Consider the following query:
SELECT col1 FROM table1
UNION ALL
SELECT col1 FROM table2
Clearly col1 comes from more than one table.
you can solve it like the following :
DataTable schemaTable = sqlReader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
foreach (DataColumn column in schemaTable.Columns)
{
MessageBox.Show (string.Format("{0} = {1}", column.ColumnName, row[column]));
}
}
SqlCeConnection conn = new SqlCeConnection("Data Source = Database1.sdf");
SqlCeCommand query = conn.CreateCommand();
query.CommandText = "myTableName";
query.CommandType = CommandType.TableDirect;
conn.Open();
SqlCeDataReader myreader = query.ExecuteReader(CommandBehavior.KeyInfo);
DataTable myDataTable= myreader.GetSchemaTable();
//thats the code you asked. in the loop
for (int i = 0; i < myDataTable.Rows.Count; i++)
{
listView1.Columns.Add(myDataTable.Rows[i][0].ToString());
}
How to get database name, table name & column name.
Also possible to get Schema name as well. Tested with MS SQL 2016
CommandBehavior.KeyInfo must be indicated
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.KeyInfo);
DataTable dataTable = sqlDataReader.GetSchemaTable();
for (int i = 0; i < dataTable.Rows.Count - 1; i++)
{
string ii =
dataTable.Rows[i]["BaseCatalogName"].ToString() + "\\" +
dataTable.Rows[i]["BaseTableName"].ToString() + "\\" +
dataTable.Rows[i]["ColumnName"].ToString();
}