我知道我可以使用SMO找到Table Rowcount,但是我无法获得View Rowcount ..我真的不需要精确的rowcount(这是奖金),但我确实需要知道该视图是"空" (0条记录)。
到目前为止,这是我的尝试:
public Int64 GetRowCount()
{
SqlConnection sqlConnection = new SqlConnection(SqlConnectionString);
ServerConnection serverConnection = new ServerConnection(sqlConnection);
Server server = new Server(serverConnection);
if (server == null)
throw new InvalidDataException(
string.Format(
"Could not connect to server {0}. Check that it exists and that the current user has access to it.",
SqlServerName));
Database db = server.Databases[SqlDatabaseName];
if (db == null)
throw new InvalidDataException(
string.Format(
"Could not connect to database {0} on server {1}. Check that it exists and that the current user has access to it.",
SqlDatabaseName, SqlServerName));
db.DefaultSchema = SqlSchemaName;
if (db.Tables.Contains(SqlTableName))
{
Table tbl = db.Tables[SqlTableName];
return tbl.RowCount;
}
if (db.Views.Contains(SqlTableName))
{
View view = db.Views[SqlTableName];
try
{
view.ReCompileReferences();
}
catch
{
// ignored
}
return view.RowCount; ************************** MAGIC GOES HERE
}
throw new InvalidDataException(string.Format( "The SQL table/view {0} does not exist in database {1}, or is not accessible by the current user.",
SqlTableName, SqlDatabaseName));
}
答案 0 :(得分:1)
如果找不到其他方法,可以始终使用ExecuteWithResults方法选择单行和单个字段。然后,您可以检查结果以查看它是否返回任何行。
var server = new Server();
var db = server.Databases("northwind");
var results = db.ExecuteWithResults("select top 1 ID from [ViewName]");
答案 1 :(得分:1)
只需使用Ado.Net连接执行命令:
var cmd = sqlConnection.CreateCommand();
cmd.CommandText = string.Format(@"if exists(select * from {0})
select 1 as exist
else
select 0 as exist", SqlTableName);
var result = (int)cmd.ExecuteScalar();
如果结果== 1则存在一些记录
答案 2 :(得分:1)
我认为答案是"没有"除非视图是索引(或物化)视图。我这样说是因为SMO似乎在查看sys.partitions中的元数据以确定行数,除非视图下面的数据持久存储到磁盘,否则不会存在任何行。只有在对视图编制索引时才会发生这种情况。