gpt4 book ai didi

c# - 如何在ado.net中使用输出参数和选择sql server存储过程的查询结果?

转载 作者:太空宇宙 更新时间:2023-11-03 10:47:55 26 4
gpt4 key购买 nike

您好,我想获取输出参数的值以及选择查询的结果集。
我使用了 ExecuteNonQuery,它为输出参数提供了正确的值。
我使用 ExecuteReader 它没有为输出参数提供正确的值,但它为选择查询提供了正确的值。
那么我应该使用什么来获得这两个结果。

    ALTER PROCEDURE [dbo].[XYZ] 
(
@szUserName varchar(50),
@iOutDistinceBankCount int out
)
AS
BEGIN
declare @iCountDistinctBanks int;
set @iCountDistinctBanks = (select count (distinct a.DCC_BANK_ID )
from DEF a with(nolock)
join ABC b with(nolock) on
a.ROLEID = b.ROLEID
where b.USERNAME = @szUserName and b.STATUS_ID = 2)

if ((@iCountDistinctBanks > 1) or (@iCountDistinctBanks = 0))
begin
set @iOutDistinceBankCount = @iCountDistinctBanks
end

else
begin
set @iOutDistinceBankCount = 1;
select a.DCC_BANK_ID as DCC_BANK_ID
from DEF a with(nolock)
join ABC b with(nolock) on
a.ROLEID = b.ROLEID
where b.USERNAME = @szUserName and b.STATUS_ID = 2
end

END

这是我的 C# 代码。

Int32 i32DistinctDCCBankCount = -1;
Int64 i64BankStaticID = -1;
InitDB();
m_command = new SqlCommand("DCC_spUIDCCBankIdAccordingUser", m_con);
m_command.Parameters.Add("@szUserName", System.Data.SqlDbType.VarChar, 50).Value = MerchantName;

SqlParameter output = new SqlParameter("@iOutDistinceBankCount", System.Data.SqlDbType.Int);
output.Direction = System.Data.ParameterDirection.Output;
m_command.Parameters.Add(output);

m_command.CommandType = System.Data.CommandType.StoredProcedure;
m_con.Open();
// m_reader = m_command.ExecuteReader();
m_command.ExecuteNonQuery();
i32DistinctDCCBankCount = Convert.ToInt32(m_command.Parameters["@iOutDistinceBankCount"].Value);


if (i32DistinctDCCBankCount == 0)
{
iDistinctDCCBankCount = 0;
return i32DistinctDCCBankCount;
}
else if (i32DistinctDCCBankCount > 1)
{
iDistinctDCCBankCount = i32DistinctDCCBankCount;
return -2;
}
else if (i32DistinctDCCBankCount == 1)
{
i64BankStaticID = Convert.ToInt64(m_reader["DCC_BANK_ID"]);
iDistinctDCCBankCount = i32DistinctDCCBankCount;
return i64BankStaticID;
}


iDistinctDCCBankCount = 0;
return 0;

最佳答案

可以使用 Command.ExecuteReader(或者 ExecuteNonQuery ,如果您没有要处理的行集)直接执行相同的查询, 但是您还需要采取其他几个步骤来处理返回值。请记住,您必须在 try catch 返回值或 OUTPUT 参数之前完成对所有行集的处理。以下代码显示如何使用 ExecuteReader 和循环来处理行集,然后捕获返回值和 OUTPUT 参数。您会发现 OUTPUT 参数(甚至很多参数)的处理速度甚至比 SELECT 返回的单行数据快得多。

这里是例子

    With cmd.Parameters
cn.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
' Process rowset(s)
bolEOF = dr.Read
Do
Do While bolEOF = True
' Process rows
bolEOF = dr.Read()
Loop
Loop While dr.NextResult = True
cmd.Cancel()
// you need to close dataReader first
dr.Close()


Debug.WriteLine("@iOutDistinceBankCount:" & _
.Item("@iOutDistinceBankCount").Value.ToString)
End With

关于c# - 如何在ado.net中使用输出参数和选择sql server存储过程的查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22728814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com