当sql视图不存在时c#中断

时间:2013-11-01 18:44:39

标签: c# sql sql-server views

我在C#中有这个功能,它应该从数据库视图中提取公司特定数据并在屏幕上显示该信息。如果出现故障,此函数中的catch语句将显示错误的弹出消息。如果我在其数据库上没有AGENT_NAMES视图的客户端服务器上运行此代码,则该函数将显示以下错误:“此时无法建立连接”。我宁愿使用函数来确定数据库中是否存在视图,如果不存在,则优雅地转义。我该怎么做?

编辑:正在使用的DBMS是Microsoft SQL Server

private string getAgencyInfo()
{
    string agentNo = null;
    string agencyInfo = "";

    try
    {
        agentNo = Session["Variable_AgencyID"].ToString();
    }
    catch
    {
        this.lblPopMsg.Text = "Connection timed out, Please Login";
        this.ModalPopupExtender1.Show();
        return agencyInfo;
    }

    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ARConnectionString"].ToString()))
    {
        try
        {
            cn.Open();
        }
        catch
        {
            clearLabels();
            this.txtZipCode.Visible = false;
            this.lblZipCode.Visible = false;
            this.lblPopMsg.Text = "Unable to make a Connection at this Time";
            this.ModalPopupExtender1.Show();
            this.txtPolicyNo.Focus();
            return agencyInfo;
        }

        try
        {
            string agentData = "SELECT AGENT_NAMES.NAME FROM AGENT_NAMES WHERE AGENT_NAMES.AGENT_NO = @agentNo";

            SqlCommand command = new SqlCommand(agentData, cn);
            command.Parameters.Add(new SqlParameter("agentNo", agentNo));
            SqlDataReader dataReader = command.ExecuteReader();
            DataTable dataTable = new DataTable();

            dataTable.Load(dataReader);
            if (dataTable.Rows.Count != 0)
                agencyInfo = dataTable.Rows[0][0].ToString() + " — Agent #" + agentNo;

            return agencyInfo;
        }
        catch
        {
            clearLabels();
            this.txtZipCode.Visible = false;
            this.lblZipCode.Visible = false;
            this.lblPopMsg.Text = "Unable to make a Connection at this Time";
            this.ModalPopupExtender1.Show();
            this.txtPolicyNo.Focus();
            return agencyInfo;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以捕获SqlException,然后检查特定的错误号:

    catch (SqlException exSQL)
    {
        // want to check for number 10034 table or view doesn't exist
        if (exSQL.Number == 10034)
        {
          this.lblPopMsg.Text = "view or table doesn't exist.";
        }
   }

要查看所有数字,您可以在master数据库上运行SQL查询:

SELECT * FROM master.dbo.sysmessages

答案 1 :(得分:0)

您可以对DB-schema运行查询以检查视图是否存在。 请检查此http://technet.microsoft.com/en-us/library/ms190324.aspx

答案 2 :(得分:0)

您应该进行额外的查询以查看视图是否存在,然后明确处理该条件。

以下是查看您的观点是否存在的查询:

select * from sys.views where name = 'AGENT_NAMES'

每次查询代理名称时都不会执行此操作,或者您将进行两次数据库调用。只需在应用程序加载时执行一次。