簡體   English   中英

使用Sql Management Objects(SMO)連接到SQL,如何查看視圖是否有任何行?

[英]Using Sql Management Objects (SMO) to connect to SQL, how can I find out if a view has any rows?

我知道我可以使用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));
}

如果找不到其他方法,則始終可以使用ExecuteWithResults方法選擇單行和單個字段。 然后,您可以檢查結果以查看它是否返回任何行。

 var server = new Server();
 var db = server.Databases("northwind");
 var results = db.ExecuteWithResults("select top 1 ID from [ViewName]");

只需使用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();

如果result == 1則存在一些記錄

除非視圖是索引(或物化)視圖,否則我認為答案是“否”。 我這樣說是因為SMO似乎在查看sys.partitions中的元數據以確定行數,除非視圖下面的數據持久存儲到磁盤,否則不會存在任何行。 只有在索引視圖時才會發生這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM