我在SQL Server中有一个现有的存储过程,我需要从我的C#代码调用并获得结果。这是SP的样子
CREATE PROCEDURE [dbo].[sp_MSnextID_DDB_NextID]
@tablesequence varchar(40)
AS
declare @next_id integer
begin transaction
update DDB_NextID
set DDB_SEQUENCE = DDB_SEQUENCE + 1
where DDB_TABLE = @tablesequence
select @next_id = DDB_SEQUENCE from DDB_NextID
where DDB_TABLE = @tablesequence
commit transaction
RETURN @next_id
这是我的C#代码
using (OdbcConnection connection = new OdbcConnection(GetConnectionString()))
{
using (IDbCommand command = new OdbcCommand())
{
command.CommandText = "sp_MSnextID_DDB_NEXTID";
command.CommandType = CommandType.StoredProcedure;
IDbDataParameter parameter1 = command.CreateParameter();
parameter1.DbType = DbType.String;
parameter1.ParameterName = "@tablesequence";
parameter1.Value = "ddb_dc_document";
parameter1.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter1);
IDbDataParameter parameter2 = command.CreateParameter();
parameter2.DbType = DbType.Int32;
parameter2.ParameterName = "@Return_Value";
parameter2.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(parameter2);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
IDbDataParameter o = (command.Parameters)["@Return_Value"] as IDbDataParameter;
//Got return value from SP in o.Value
}
}
问题是我得到了异常
[42000] [Microsoft] [SQL Native Client] [SQL Server]过程或函数'sp_MSnextID_DDB_NextID'需要参数'@tablesequence', 没有提供。
我无法解释或修复。我缺少什么?
为了找到解决方法,我尝试了不同的方法:执行以下查询,在临时表中设置数据
create table #temp (i integer); insert into #temp exec sp_MSNextID_DDB_NEXTID @tablesequence='ddb_dc_document';select * from #temp;
在这种情况下,SP正确执行但select选择返回零行!
答案 0 :(得分:1)
不幸的是,you can't use named parameters with OdbcCommand
。 You will need to instead execute a call statement to your stored procedure.
using (OdbcConnection connection = new OdbcConnection(GetConnectionString()))
{
using (IDbCommand command = new OdbcCommand())
{
command.CommandText = "{ ? = CALL sp_MSnextID_DDB_NEXTID(?) }";
command.CommandType = CommandType.StoredProcedure;
IDbDataParameter parameter2 = command.CreateParameter();
parameter2.DbType = DbType.Int32;
parameter2.ParameterName = "@Return_Value";
parameter2.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(parameter2);
IDbDataParameter parameter1 = command.CreateParameter();
parameter1.DbType = DbType.String;
parameter1.ParameterName = "@tablesequence";
parameter1.Value = "ddb_dc_document";
parameter1.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter1);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
IDbDataParameter o = (command.Parameters)["@Return_Value"] as IDbDataParameter;
//Got return value from SP in o.Value
}
}
答案 1 :(得分:0)
要使解决方法正常工作,您应该替换
RETURN @next_id
在您的程序中
SELECT @next_id