9

我试过下面的代码来检查 SP 是否已经存在。如果不存在,我正在创建..

但是每次都显示 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
}
4

12 回答 12

16

尝试:

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;
            }
        }
    }
}
于 2012-12-10T09:06:43.883 回答
7

对于那些使用实体框架和 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!)。为了防止这种情况,请使用参数化语句。上述方法的问题在这里描述

解决方案是将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();
}
于 2016-05-24T12:22:23.583 回答
5

我在MSDN上找到了这个

select * from sys.objects where type_desc = 'SQL_STORED_PROCEDURE' AND name = 'Sql_PersonInsert'
于 2012-12-10T09:05:04.207 回答
3

尝试:

SELECT * 
FROM sys.objects 
WHERE object_id = OBJECT_ID(N'GP_SOP_AdjustTax') AND type in (N'P', N'PC')
于 2012-12-10T09:05:01.353 回答
3

我的尝试:

  • 可重复使用的扩展方法
  • 最小的 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();
  }
}
于 2016-11-04T15:51:45.950 回答
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”为您提供存储过程。

于 2014-03-07T13:41:14.980 回答
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;
                    }
                }
            }
        }
于 2012-12-10T09:04:57.717 回答
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;  
          }
      }
 }
于 2012-12-10T11:12:09.647 回答
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();
            }
        }
    }
}
于 2020-06-15T06:58:16.973 回答
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;
    }
}
于 2020-09-02T09:01:32.660 回答
0

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

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

于 2021-07-01T16:13:01.527 回答
-1

尝试这个;

if object_id('YourStoredProcedureName') is null
    exec ('create procedure dbo.YourSp as select 1')
go
alter procedure dbo.YourStoredProcedure
as
于 2012-12-10T09:07:33.470 回答