在C#中使用存储过程输出参数
我在将输出参数从Sql Server存储过程返回到C#变量时遇到问题。我已经阅读了有关此内容的其他帖子,不仅在这里,而且在其他网站上,我无法让它工作。这是我现在拥有的。目前我只是想打印回来的价值。以下代码返回null值。我试图返回的是主键。我尝试过使用@@IDENTITY
和SCOPE_INDENTITY()
(即SET @NewId = SCOPE_IDENTITY()
)。
存储过程:
CREATE PROCEDURE usp_InsertContract @ContractNumber varchar(7), @NewId int OUTPUT ASBEGIN INSERT into [dbo].[Contracts] (ContractNumber) VALUES (@ContractNumber) Select @NewId = Id From [dbo].[Contracts] where ContractNumber = @ContractNumberEND
打开数据库:
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;}
执行命令:
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); }}
慕的地8271018
相关分类