如何在C#程序中执行存储过程
我想从一个C#程序执行这个存储过程 我在SqlServer查询窗口中编写了以下存储过程,并将其另存为 仓库1:如何在C#程序中执行存储过程,c#,sql-server,stored-procedures,C#,Sql Server,Stored Procedures,我想从一个C#程序执行这个存储过程 我在SqlServer查询窗口中编写了以下存储过程,并将其另存为 仓库1: use master go create procedure dbo.test as DECLARE @command as varchar(1000), @i int SET @i = 0 WHILE @i < 5 BEGIN Print 'I VALUE ' +CONVERT(varchar(20),@i) EXEC(@command) SET @i = @i + 1 E
use master
go
create procedure dbo.test as
DECLARE @command as varchar(1000), @i int
SET @i = 0
WHILE @i < 5
BEGIN
Print 'I VALUE ' +CONVERT(varchar(20),@i)
EXEC(@command)
SET @i = @i + 1
END
这将显示异常找不到存储过程dbo.test
。我需要提供路径吗?如果是,存储过程应存储在哪个位置
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
}
以下是一些有趣的链接,您可以阅读:
- 您的意思是您的代码是DDL?
如果是这样,MSSQL没有区别。上面的例子很好地展示了如何调用它。确保
CommandType = CommandType.Text
在C#中调用存储过程
SqlCommand cmd=newsqlcommand(“StoreProcedureName”,con);
cmd.CommandType=CommandType.storedProcess;
cmd.Parameters.AddWithValue(“@value”,txtValue.Text);
con.Open();
int rowInfected=cmd.ExecuteNonQuery();
con.Close();
这里没有答案。所以我加了一个
using Dapper;
using System.Data.SqlClient;
using (var cn = new SqlConnection(@"Server=(local);DataBase=master;Integrated Security=SSPI"))
cn.Execute("dbo.test", commandType: CommandType.StoredProcedure);
使用Ado.net
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace PBDataAccess
{
public class AddContact
{
// for preparing connection to sql server database
private SqlConnection conn;
// for preparing sql statement or stored procedure that
// we want to execute on database server
private SqlCommand cmd;
// used for storing the result in datatable, basically
// dataset is collection of datatable
private DataSet ds;
// datatable just for storing single table
private DataTable dt;
// data adapter we use it to manage the flow of data
// from sql server to dataset and after fill the data
// inside dataset using fill() method
private SqlDataAdapter da;
// created a method, which will return the dataset
public DataSet GetAllContactType()
{
// retrieving the connection string from web.config, which will
// tell where our database is located and on which database we want
// to perform opearation, in this case we are working on stored
// procedure so you might have created it somewhere in your database.
// connection string will include the name of the datasource, your
// database name, user name and password.
using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
.ConnectionString))
{
// Addcontact is the name of the stored procedure
using (cmd = new SqlCommand("Addcontact", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// here we are passing the parameters that
// Addcontact stored procedure expect.
cmd.Parameters.Add("@CommandType",
SqlDbType.VarChar, 50).Value = "GetAllContactType";
// here created the instance of SqlDataAdapter
// class and passed cmd object in it
da = new SqlDataAdapter(cmd);
// created the dataset object
ds = new DataSet();
// fill the dataset and your result will be
stored in dataset
da.Fill(ds);
}
}
return ds;
}
}
****** Stored Procedure ******
CREATE PROCEDURE Addcontact
@CommandType VARCHAR(MAX) = NULL
AS
BEGIN
IF (@CommandType = 'GetAllContactType')
BEGIN
SELECT * FROM Contacts
END
END
请查看Crane(我是作者)
还有一系列您可能喜欢的其他功能 这是一个存储过程的示例,它返回一个值并在c中执行#
这是通过反射执行带参数和不带参数的存储过程的代码。 请注意,对象属性名称需要与存储过程的参数匹配
private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
private SqlConnection Conn = new SqlConnection(ConnString);
public void ExecuteStoredProcedure(string procedureName)
{
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
public void ExecuteStoredProcedure(string procedureName, object model)
{
var parameters = GenerateSQLParameters(model);
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
foreach (var param in parameters)
{
sqlCmd.Parameters.Add(param);
}
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
private List<SqlParameter> GenerateSQLParameters(object model)
{
var paramList = new List<SqlParameter>();
Type modelType = model.GetType();
var properties = modelType.GetProperties();
foreach (var property in properties)
{
if (property.GetValue(model) == null)
{
paramList.Add(new SqlParameter(property.Name, DBNull.Value));
}
else
{
paramList.Add(new SqlParameter(property.Name, property.GetValue(model)));
}
}
return paramList;
}
private static string ConnString=ConfigurationManager.ConnectionStrings[“SqlConnection”].ConnectionString;
私有SqlConnection Conn=新的SqlConnection(ConnString);
public void ExecuteStoredProcedure(字符串过程重命名)
{
SqlConnection sqlConnObj=新的SqlConnection(ConnString);
SqlCommand sqlCmd=新的SqlCommand(procedureName,sqlConnObj);
sqlCmd.CommandType=CommandType.StoredProcess;
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
public void ExecuteStoredProcedure(字符串过程重命名,对象模型)
{
var参数=GenerateSQLParameters(模型);
SqlConnection sqlConnObj=新的SqlConnection(ConnString);
SqlCommand sqlCmd=新的SqlCommand(procedureName,sqlConnObj);
sqlCmd.CommandType=CommandType.StoredProcess;
foreach(参数中的var参数)
{
sqlCmd.Parameters.Add(param);
}
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
私有列表GenerateSQLParameters(对象模型)
{
var paramList=新列表();
类型modelType=model.GetType();
var properties=modelType.GetProperties();
foreach(属性中的var属性)
{
if(property.GetValue(model)==null)
{
Add(新的SqlParameter(property.Name,DBNull.Value));
}
其他的
{
添加(新的SqlParameter(property.Name,property.GetValue(model));
}
}
返回参数列表;
}
使用整洁的方式。所以我加了这个,希望有人能帮忙
public void Insert(ProductName obj)
{
SqlConnection connection = new SqlConnection(Connection.GetConnectionString());
connection.Open();
connection.Execute("ProductName_sp", new
{ @Name = obj.Name, @Code = obj.Code, @CategoryId = obj.CategoryId, @CompanyId = obj.CompanyId, @ReorderLebel = obj.ReorderLebel, @logo = obj.logo,@Status=obj.Status, @ProductPrice = obj.ProductPrice,
@SellingPrice = obj.SellingPrice, @VatPercent = obj.VatPercent, @Description=obj.Description, @ColourId = obj.ColourId, @SizeId = obj.SizeId,
@BrandId = obj.BrandId, @DisCountPercent = obj.DisCountPercent, @CreateById =obj.CreateById, @StatementType = "Create" }, commandType: CommandType.StoredProcedure);
connection.Close();
}
我所做的,在我的例子中,我想在dataGridView中显示过程的结果:
using (var command = new SqlCommand("ProcedureNameHere", connection) {
// Set command type and add Parameters
CommandType = CommandType.StoredProcedure,
Parameters = { new SqlParameter("@parameterName",parameterValue) }
})
{
// Execute command in Adapter and store to dataset
var adapter = new SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
// Display results in DatagridView
dataGridView1.DataSource = dataset.Tables[0];
}
最简单、最直接的
SqlCommand cmd = new SqlCommand("StoreProcedureName",con); // Just like you declared it
cmd.CommandType = CommandType.StoredProcedure; // an attribute related to the object
cmd.Parameters.AddWithValue("@value",txtValue.Text); // Parameter name and text source
con.Open();
int rowAffected = cmd.ExecuteNonQuery();
con.Close();
我担心cmd.CommandText=“Stored1”如何解释我的存储过程。我不知道。“CommandText”必须设置为存储过程的名称,然后从C#执行,就像执行了“exec StoredProcedureName”在SSMS中-或者您担心什么?我如何为上述存储过程提供storedprocedure名称?请您告诉我??因此,首先,您必须创建存储过程,对于您拥有的代码,您需要添加:“create procedure dbo.NameOfYourStoredProcedureHere as”在beginning@Cute:如果将其作为存储过程,则必须有名称!“创建过程(procedurename)”调用中使用的名称。如果没有,那么就没有存储过程(只有一批T-SQL语句),就不能使用“CommandType=StoredProcedure”,显然,您甚至可以摆脱
conn.Close
,这是由Dispose
所暗示的,在这种情况下也是如此。我喜欢有匹配的打开
和关闭
调用。如果您说,将来将连接对象重构为字段并删除using语句,您可能会意外忘记添加Close
,最终导致连接打开。如果存储的过程需要参数,您将如何执行此操作?只需使用相同的名称和类型将参数添加到命令对象?@Dani Yes。只需将参数添加到SqlCommand
对象的parameters
集合中。我是否能够在SP中发送下拉值选项?您应该真正使用“using”关键字。将打开/关闭责任推到框架上。SqlCommand的定义:公共密封类SqlCommand:System.Data.Common.DbCommand,IClonable,IDisposable
。使用语句将其放入中将有助于清理。您最好使用master以外的数据库,甚至用于测试。这是一个系统数据库,最终会导致问题。在SQL 2012中,它不允许我在那里创建表。相反,它将允许我创建存储过程:/尽管有答案:您是否检查了sp是否实际使用您提供的名称(dbo.test)创建?我不知道如果非dbo用户尝试创建dbo.test会发生什么。。。它会被创建为非dbo.test吗?@obayhan这个问题是在你声称它可能是的复制品之前两年提出的。请在以后将最近的问题标记为重复问题。您的注释行已断开,并且如果您可以在注释中提供对我们有好处的存储过程。如果您在代码中添加了存储过程,请将其签出。这不起作用。这个过时了吗?我找不到方法过程。我已更新examp
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
var result = sqlAccess.Command().ExecuteNonQuery("StoredProcedureName");
CREATE PROCEDURE [dbo].[InsertPerson]
-- Add the parameters for the stored procedure here
@FirstName nvarchar(50),@LastName nvarchar(50),
@PersonID int output
AS
BEGIN
insert [dbo].[Person](LastName,FirstName) Values(@LastName,@FirstName)
set @PersonID=SCOPE_IDENTITY()
END
Go
--------------
// Using stored procedure in adapter to insert new rows and update the identity value.
static void InsertPersonInAdapter(String connectionString, String firstName, String lastName) {
String commandText = "dbo.InsertPerson";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlDataAdapter mySchool = new SqlDataAdapter("Select PersonID,FirstName,LastName from [dbo].[Person]", conn);
mySchool.InsertCommand = new SqlCommand(commandText, conn);
mySchool.InsertCommand.CommandType = CommandType.StoredProcedure;
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName"));
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("@LastName", SqlDbType.NVarChar, 50, "LastName"));
SqlParameter personId = mySchool.InsertCommand.Parameters.Add(new SqlParameter("@PersonID", SqlDbType.Int, 0, "PersonID"));
personId.Direction = ParameterDirection.Output;
DataTable persons = new DataTable();
mySchool.Fill(persons);
DataRow newPerson = persons.NewRow();
newPerson["FirstName"] = firstName;
newPerson["LastName"] = lastName;
persons.Rows.Add(newPerson);
mySchool.Update(persons);
Console.WriteLine("Show all persons:");
ShowDataTable(persons, 14);
private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
private SqlConnection Conn = new SqlConnection(ConnString);
public void ExecuteStoredProcedure(string procedureName)
{
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
public void ExecuteStoredProcedure(string procedureName, object model)
{
var parameters = GenerateSQLParameters(model);
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
foreach (var param in parameters)
{
sqlCmd.Parameters.Add(param);
}
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
private List<SqlParameter> GenerateSQLParameters(object model)
{
var paramList = new List<SqlParameter>();
Type modelType = model.GetType();
var properties = modelType.GetProperties();
foreach (var property in properties)
{
if (property.GetValue(model) == null)
{
paramList.Add(new SqlParameter(property.Name, DBNull.Value));
}
else
{
paramList.Add(new SqlParameter(property.Name, property.GetValue(model)));
}
}
return paramList;
}
public void Insert(ProductName obj)
{
SqlConnection connection = new SqlConnection(Connection.GetConnectionString());
connection.Open();
connection.Execute("ProductName_sp", new
{ @Name = obj.Name, @Code = obj.Code, @CategoryId = obj.CategoryId, @CompanyId = obj.CompanyId, @ReorderLebel = obj.ReorderLebel, @logo = obj.logo,@Status=obj.Status, @ProductPrice = obj.ProductPrice,
@SellingPrice = obj.SellingPrice, @VatPercent = obj.VatPercent, @Description=obj.Description, @ColourId = obj.ColourId, @SizeId = obj.SizeId,
@BrandId = obj.BrandId, @DisCountPercent = obj.DisCountPercent, @CreateById =obj.CreateById, @StatementType = "Create" }, commandType: CommandType.StoredProcedure);
connection.Close();
}
using (var command = new SqlCommand("ProcedureNameHere", connection) {
// Set command type and add Parameters
CommandType = CommandType.StoredProcedure,
Parameters = { new SqlParameter("@parameterName",parameterValue) }
})
{
// Execute command in Adapter and store to dataset
var adapter = new SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
// Display results in DatagridView
dataGridView1.DataSource = dataset.Tables[0];
}
SqlCommand cmd = new SqlCommand("StoreProcedureName",con); // Just like you declared it
cmd.CommandType = CommandType.StoredProcedure; // an attribute related to the object
cmd.Parameters.AddWithValue("@value",txtValue.Text); // Parameter name and text source
con.Open();
int rowAffected = cmd.ExecuteNonQuery();
con.Close();