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

Kav*_*tha 7 c# sql sql-server stored-procedures

我尝试下面的代码为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
}
Run Code Online (Sandbox Code Playgroud)

Sir*_*ifi 13

尝试:

if exists(select * from sys.objects where type = 'p' and name = '<procedure name>' )
Run Code Online (Sandbox Code Playgroud)

你也可以用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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


The*_*Kid 5

我在MSDN上找到了这个

select * from sys.objects where type_desc = 'SQL_STORED_PROCEDURE' AND name = 'Sql_PersonInsert'
Run Code Online (Sandbox Code Playgroud)


Har*_*lse 5

对于那些使用Entity Framework和DbContext的人:

为DbContext创建一个扩展类:

internal static class DbContextExtensions
{
    public static bool StoredProcedureExists(this DbContext context,
        string procedureName)
    {
        string query = String.Format(
            @"select top 1 from sys.procedures " +
              "where [type_desc] = '{0}'", procedureName);
        return dbContext.Database.SqlQuery<string>(query).Any();
    }
}
Run Code Online (Sandbox Code Playgroud)

作为robIII说,这个代码不应该,因为它使数据库容易受到黑客发布到外部世界(谢谢RobIII!).为了防止这种情况,请使用参数化语句.这里描述了上述方法的问题

解决方案是将procedureName 作为参数放在SQL语句中.SQL将检查字符串参数是否具有所需的格式,从而禁止恶意调用:

public static bool ImprovedExists(this DbContext dbContext, string procedureName)
{
    object[] functionParameters = new object[]
    {
        new SqlParameter(@"procedurename", procedureName),
    };
    const string query = @"select [name] from sys.procedures where name= @procedurename";
    return dbContext.Database.SqlQuery<string>(query, functionParameters).Any();
}
Run Code Online (Sandbox Code Playgroud)

  • [能否检查一下存储过程“`'; drop table users; --`”是否存在?](https://xkcd.com/327/) ;-) 使用[参数化语句](https://en. wikipedia.org/wiki/SQL_injection)! (2认同)