[英]Output parameter issue in sql server and c#
為什么如果我使用輸出參數創建此存儲過程,我收到以下錯誤:
sp_DTS_InsertLSRBatch需要未提供的參數@ErrorMsg
存儲過程代碼:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[sp_DTS_InsertLSRBatch]
@LSRNbr varchar(10),
@BatchNbr varchar(10),
@ErrorMsg varchar(20) output
AS
BEGIN
SET NOCOUNT ON;
if not exists(select *
from tblDTS_LSRBatch (nolock)
where LSRNbr=@LSRNbr and BatchNbr=@BatchNbr)
begin
-- check if BatchNbr exists under another LSR
-- if not add (LSR, BatchNbr) else error
if not exists(select *
from tblDTS_LSRBatch (nolock)
where BatchNbr=@BatchNbr)
insert into tblDTS_LSRBatch (LSRNbr,BatchNbr) values (@LSRNbr, @BatchNbr)
else
set @ErrorMsg = 'Batch dif LSR'
end
END
C#代碼:
SqlConnection conn = new SqlConnection(ConnStr);
try
{
conn.Open();
for (int i = 0; i <= lbxBatch.Items.Count - 1; i++)
{
SqlCommand cmd = new SqlCommand("sp_DTS_InsertLSRBatch", conn);
cmd.Parameters.Add(new SqlParameter("@LSRNbr", txtLSR.Text));
cmd.Parameters.Add(new SqlParameter("@BatchNbr", lbxBatch.Items[i].ToString()));
//Output parameter "ErrorMsg"
SqlParameter pErrorMsg = new SqlParameter("@ErrorMsg", SqlDbType.VarChar, 20);
pErrorMsg.Direction = ParameterDirection.Output;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery(); <--- ERROR
在您的代碼中,您尚未添加pErrorMsg參數。 添加此行:
cmd.Parameters.Add(pErrorMsg);
此外,在存儲過程中,必須將@ErrorMsg sql輸出變量設置為適當的值,如空字符串或SP代碼的if條件部分中的雙引號(“”),作為良好的編碼實踐。
您正在創建pErrorMsg參數,但是在哪里將其添加到命令中?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.