使用C#存储过程的输出参数 [英] Using stored procedure output parameters in C#
问题描述
我有返回从SQL Server存储过程的输出参数为C#变量的一个问题。我已阅读有关本,不仅在这里其他的职位,但在其他网站上,我不能得到它的工作。以下是我目前有。目前,我只是想打印回来的价值。下面code返回null值。我在试图返回的主键。我已经尝试使用 @@ IDENTITY
和 SCOPE_INDENTITY()
(即 SET @NewId = SCOPE_IDENTITY ()
)。
存储过程:
CREATE PROCEDURE usp_InsertContract
@ContractNumber VARCHAR(7), @NewId INT输出
如
开始 INSERT操作[DBO]。[合同(ContractNumber)
VALUES(@ContractNumber) 选择@NewId = ID从[DBO]。[合同]其中ContractNumber = @ContractNumber
结束
打开数据库:
pvConnectionString =服务器=桌面PC的\\\\ SQLEX $ P $干燥综合征;数据库= PVDatabase;用户ID = SA;
PASSWORD = *******; Trusted_Connection = TRUE;;尝试
{
pvConnection =新的SqlConnection(pvConnectionString);
pvConnection.Open();
}
赶上(例外五)
{
databaseError = TRUE;
}
执行以下命令:
pvCommand =新的SqlCommand(usp_InsertContract,pvConnection);pvCommand.Transaction = pvTransaction;
pvCommand.CommandType = CommandType.StoredProcedure;pvCommand.Parameters.Clear();
pvCommand.Parameters.Add(新的SqlParameter(@ ContractNumber,contractNumber));的SqlParameter pvNewId =新的SqlParameter();
pvNewId.ParameterName =@NewId;
pvNewId.DbType = DbType.Int32;
pvNewId.Direction = ParameterDirection.Output;
pvCommand.Parameters.Add(pvNewId);尝试
{
sqlRows = pvCommand.ExecuteNonQuery(); 如果(sqlRows大于0)
Debug.Print(新标识插入=,
pvCommand.Parameters [@ NEWID] Value.ToString());
}
赶上(例外五)
{
Debug.Print(插入异常类型:{0},e.GetType());
Debug.Print(消息:{0},e.Message);
}
}
我稍微修改您的存储过程(使用 SCOPE_IDENTITY
),它看起来是这样的:
CREATE PROCEDURE usp_InsertContract
@ContractNumber VARCHAR(7),
@NewId INT输出
如
开始
INSERT INTO [DBO]。[合同](ContractNumber)
VALUES(@ContractNumber) 选择@NewId = SCOPE_IDENTITY()
结束
我想这和它的作品只是罚款(与修改的存储过程):
//定义连接和命令,在使用块,以确保处置
使用(SqlConnection的康恩=新的SqlConnection(pvConnectionString))
用(CMD的SqlCommand =新的SqlCommand(dbo.usp_InsertContract,康涅狄格州))
{
cmd.CommandType = CommandType.StoredProcedure; //设置参数
cmd.Parameters.Add(@ ContractNumber,SqlDbType.VarChar,7);
cmd.Parameters.Add(@ NEWID,SqlDbType.Int).Direction = ParameterDirection.Output; //设置参数值
cmd.Parameters [@ ContractNumber]值= contractNumber。 //打开连接并执行存储过程
conn.Open();
cmd.ExecuteNonQuery(); //读取@NewId产值
INT contractID = Convert.ToInt32(cmd.Parameters [@ NEWID]值。);
conn.Close();
}
这是否工作在您的环境吗?我不能说,为什么你原来的code将无法正常工作 - 但我这样做的时候这里,VS2010和SQL Server 2008 R2,它只是完美的作品....
如果你没有得到一个价值 - 那么我怀疑你的表<$ C C>合同$ C C>可能没有真正与<$ C $ç> IDENTITY列属性就可以了。
I am having a problem returning an output parameter from a Sql Server stored procedure into a C# variable. I have read the other posts concerning this, not only here but on other sites, and I cannot get it to work. Here is what I currently have. Currently I am just trying to print the value that comes back. The following code returns a null value. What I an trying to return is the primary key. I have tried using @@IDENTITY
and SCOPE_INDENTITY()
(i.e. SET @NewId = SCOPE_IDENTITY()
).
Stored Procedure:
CREATE PROCEDURE usp_InsertContract
@ContractNumber varchar(7),
@NewId int OUTPUT
AS
BEGIN
INSERT into [dbo].[Contracts] (ContractNumber)
VALUES (@ContractNumber)
Select @NewId = Id From [dbo].[Contracts] where ContractNumber = @ContractNumber
END
Opening the database:
pvConnectionString = "Server = Desktop-PC\\SQLEXPRESS; Database = PVDatabase; User ID = sa;
PASSWORD = *******; Trusted_Connection = True;";
try
{
pvConnection = new SqlConnection(pvConnectionString);
pvConnection.Open();
}
catch (Exception e)
{
databaseError = true;
}
Executing the command:
pvCommand = new SqlCommand("usp_InsertContract", pvConnection);
pvCommand.Transaction = pvTransaction;
pvCommand.CommandType = CommandType.StoredProcedure;
pvCommand.Parameters.Clear();
pvCommand.Parameters.Add(new SqlParameter("@ContractNumber", contractNumber));
SqlParameter pvNewId = new SqlParameter();
pvNewId.ParameterName = "@NewId";
pvNewId.DbType = DbType.Int32;
pvNewId.Direction = ParameterDirection.Output;
pvCommand.Parameters.Add(pvNewId);
try
{
sqlRows = pvCommand.ExecuteNonQuery();
if (sqlRows > 0)
Debug.Print("New Id Inserted = ",
pvCommand.Parameters["@NewId"].Value.ToString());
}
catch (Exception e)
{
Debug.Print("Insert Exception Type: {0}", e.GetType());
Debug.Print(" Message: {0}", e.Message);
}
}
I slightly modified your stored procedure (to use SCOPE_IDENTITY
) and it looks like this:
CREATE PROCEDURE usp_InsertContract
@ContractNumber varchar(7),
@NewId int OUTPUT
AS
BEGIN
INSERT INTO [dbo].[Contracts] (ContractNumber)
VALUES (@ContractNumber)
SELECT @NewId = SCOPE_IDENTITY()
END
I tried this and it works just fine (with that modified stored procedure):
// define connection and command, in using blocks to ensure disposal
using(SqlConnection conn = new SqlConnection(pvConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.usp_InsertContract", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("@ContractNumber", SqlDbType.VarChar, 7);
cmd.Parameters.Add("@NewId", SqlDbType.Int).Direction = ParameterDirection.Output;
// set parameter values
cmd.Parameters["@ContractNumber"].Value = contractNumber;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from @NewId
int contractID = Convert.ToInt32(cmd.Parameters["@NewId"].Value);
conn.Close();
}
Does this work in your environment, too? I can't say why your original code won't work - but when I do this here, VS2010 and SQL Server 2008 R2, it just works flawlessly....
If you don't get back a value - then I suspect your table Contracts
might not really have a column with the IDENTITY
property on it.
这篇关于使用C#存储过程的输出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!