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

时间:2012-12-10 08:59:44

标签: 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
}

12 个答案:

答案 0 :(得分:13)

尝试:

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;
            }
        }
    }
}

答案 1 :(得分:5)

我在MSDN

上找到了这个
select * from sys.objects where type_desc = 'SQL_STORED_PROCEDURE' AND name = 'Sql_PersonInsert'

答案 2 :(得分: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();
    }
}

正如robIII所说,这段代码不应该发布到外面的世界,因为它使数据库容易受到黑客攻击(谢谢RobIII!)。为了防止这种情况,请使用参数化语句。 The problem with the above mentioned method is described here

解决方案是将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();
}

答案 3 :(得分:2)

您可以使用以下tsql查询(适用于SQL Server)进行检查:

select * from sysobjects where ytype='P' and name='MyStoredProcedureName'

如果查询返回行,则存在名为“MyStoredProcedureName”的存储过程。

以下是您在代码中使用它的方法:

        //TODO: set connection string
        string connString = "";
        string query = "select * from sysobjects where ytype='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;
                    }
                }
            }
        }

答案 4 :(得分:2)

尝试:

SELECT * 
FROM sys.objects 
WHERE object_id = OBJECT_ID(N'GP_SOP_AdjustTax') AND type in (N'P', N'PC')

答案 5 :(得分:2)

string checkSP = String.Format(
  "IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'", 
  "GP_SOP_AdjustTax");
如果你将'U'改为'P',

就可以了。 使用'U'可以查询用户表,其中'P'为您提供存储过程。

答案 6 :(得分:2)

我刺伤了它:

  • 可重复使用的扩展方法
  • 最小Sql /最小C#
  • 作为OP隐式请求从.Net调用
  • 由于object_id功能
  • 可能会更快
public static bool StoredProcedureExists(this string source)
{
  using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
  {
    conn.Open();
    using (var cmd = new SqlCommand($"select object_id('{source}')", conn))
      return !cmd.ExecuteScalar().ToString().IsNullOrWhiteSpace();
  }
}

答案 7 :(得分:1)

private static bool StoredProcedureExists(string sp)
{    
      var connString = @"<your string here>";
      var query = string.Format("SELECT COUNT(0) FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = '{0}'", sp);
      using (var conn = new SqlConnection(connString))
      {
          conn.Open();
          using (var cmd = new SqlCommand(query, conn))
          {
              return Convert.ToInt32(cmd.ExecuteScalar()) > 0;  
          }
      }
 }

答案 8 :(得分:0)

  • 使用不同的模式处理过程名称
  • 带括号和不带括号([])的名称
  • 使用参数避免SQL注入

注意:调用方拥有SQL连接

public static class SqlConnectionExtensions
{        
    public static Task<bool> StoredProcedureExistsAsync(this SqlConnection sqlConnection, string storedProcedureName)
    {
        string query = "SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@storedProcedureName) AND type in (N'P', N'PC')";

        using (SqlCommand command = new SqlCommand(query, sqlConnection))
        {
            command.Parameters.AddWithValue("@storedProcedureName", storedProcedureName);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                return reader.ReadAsync();
            }
        }
    }
}

答案 9 :(得分:0)

以下内容适用于我认为的MySQL,SQL Server和Oracle:

SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE='PROCEDURE'
AND (ROUTINE_SCHEMA='questionnaire' OR ROUTINE_CATALOG = 'questionnaire')
AND SPECIFIC_NAME='create_question';

用法:

string procedureName = "create_question";
using (DbConnection conn = new SqlConnection("Server=localhost;Database=questionnaire;Trusted_Connection=True;")) // Connection is interchangeable
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = $"SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND (ROUTINE_SCHEMA='{conn.Database}' OR ROUTINE_CATALOG = '{conn.Database}') AND SPECIFIC_NAME='{procedureName}';";
        return cmd.ExecuteScalar() != null;
    }
}

答案 10 :(得分:0)

如果您使用 Microsoft.SqlServer.Management.Smo,请尝试

private static bool CheckIfStoredProcedureExists(Database db, string spName, string schema)
{
   db.StoredProcedures.Refresh();
   return (db.StoredProcedures[spName, schema] != null);
}

答案 11 :(得分:-1)

试试这个;

if object_id('YourStoredProcedureName') is null
    exec ('create procedure dbo.YourSp as select 1')
go
alter procedure dbo.YourStoredProcedure
as