如何使用c#代码检查sql server中是否存在存储过程

前端之家收集整理的这篇文章主要介绍了如何使用c#代码检查sql server中是否存在存储过程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试下面的代码为cheking SP是alredy存在与否.如果不存在我正在创造..

但每次显示sp都没有创建…..但我的数据库已经有了这个sp.

让我知道我在哪里做错了.

string checkSP = String.Format(
  "IF OBJECT_ID('{0}','U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'","GP_SOP_AdjustTax");

sqlCommand command = new sqlCommand(checkSP,myConnection);
command.CommandType = CommandType.Text;

if (myConnection == null || myConnection.State == ConnectionState.Closed)
{
    try
    {
        myConnection.Open();
    }
    catch (Exception a)
    {
        MessageBox.Show("Error " + a.Message);
    }
}

bool Exist = false;
Exist = Convert.ToBoolean(command.ExecuteScalar());
if (Exist == false)   //false : SP does not exist
{ 
    // here i am writing code for creating SP
}

解决方法

尝试:
if exists(select * from sys.objects where type = 'p' and name = '<procedure name>' )

你也可以用c#检查:

string connString = "";
string query = "select * from sysobjects where type='P' and name='MyStoredProcedureName'";
bool spExists = false;
using (sqlConnection conn = new sqlConnection(connString))
{
    conn.Open();
    using (sqlCommand command = new sqlCommand(query,conn))
    {
        using (sqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                spExists = true;
                break;
            }
        }
    }
}
原文链接:https://www.f2er.com/csharp/98459.html

猜你在找的C#相关文章