我想连接到SQL Server数据库,遍历所有表,然后遍历每一行和每列以获取数据库中所有数据的值。
我到目前为止:
SqlConnection sqlConn = new SqlConnection("Server = P1-012\\ECSQLEXPRESS; Database = DavidsDB; Integrated Security=True");
sqlConn.Open();
DataTable dtSchema = new DataTable();
dtSchema = sqlConn.GetSchema("tables");
foreach(DataRow drCurTable in dtSchema.Rows)
{
if (drCurTable.ItemArray[3].ToString() == "BASE TABLE")
{
// At this point I want to loop though each row in the current table
// and get the value for each column in that row.
MessageBox.Show(drCurTable.ItemArray[2].ToString());
}
}
不知怎的,我需要引用当前表,遍历每一行,然后迭代我认为的每一列。
谢谢!
大卫
答案 0 :(得分:0)
您应该调查SQL Server中的INFORMATION_SCHEMA视图。 特别是这两个将为您提供查询表格然后查询列所需的信息。
SELECT * FROM INFORMATION_SCHEMA.TABLES;
SELECT * FROM INFORMATION_SCHEMA.COLUMNS;
在纯SQL术语中,你也可以这样做......
DECLARE @sql nvarchar(max) = '';
SELECT @sql += 'SELECT * FROM [' + [TABLE_SCHEMA] + '].[' + [TABLE_NAME] + '];' FROM INFORMATION_SCHEMA.TABLES;
EXEC sp_executesql @sql;