gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:49:27 25 4
gpt4 key购买 nike

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

但是每次都显示sp is not created.....但是我的数据库已经有了这个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;
}
}
}
}

关于c# - 如何使用c#代码检查sql server中是否存在存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13797744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com