加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:24:56 所属栏目:百科 来源:网络整理
导读:我尝试下面的代码为cheking SP是alredy存在与否.如果不存在我正在创造.. 但每次显示sp都没有创建…..但我的数据库已经有了这个sp. 让我知道我在哪里做错了. string checkSP = String.Format( "IF OBJECT_ID('{0}','U') IS NOT NULL SELECT 'true' ELSE SELEC
我尝试下面的代码为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;
            }
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读