[英]Returning SQL Server Output parameter to C# by Stored Procedure
I have a stored procedure in SQL Server 2012 with an OUTPUT
parameter. 我在SQL Server 2012中具有带OUTPUT
参数的存储过程。 When I call the c# decrypt function, at the point when I hit ExecuteNonQuery()
, I always get the error: 当我调用c#解密函数时,当我点击ExecuteNonQuery()
,总是会收到错误:
Procedure or function 'DecryptCCode' expects parameter '@decryptedStr', which was not supplied. 过程或函数'DecryptCCode'需要未提供的参数'@decryptedStr'。
How do I get the OUTPUT
value of my stored procedure in code? 如何在代码中获取存储过程的OUTPUT
值? Thanks. 谢谢。
Stored procedure: 存储过程:
ALTER PROCEDURE [dbo].[DecryptCCode]
@decryptedStr nchar(5) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS
(SELECT * FROM sys.symmetric_keys WHERE symmetric_key_id = 101)
CREATE MASTER KEY ENCRYPTION BY
PASSWORD = 'rfsdffsssdfsdfwerefeses'
IF NOT EXISTS
(SELECT * FROM sys.certificates WHERE name='ClientCert')
CREATE CERTIFICATE ClientCert
WITH SUBJECT = 'My ClientCode Certificate';
IF NOT EXISTS
(SELECT * FROM sys.symmetric_keys WHERE name='ClientCode_K1')
CREATE SYMMETRIC KEY ClientCode_K1
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE ClientCert;
OPEN SYMMETRIC KEY ClientCode_K1
DECRYPTION BY CERTIFICATE ClientCert;
SELECT
@decryptedStr = CONVERT(nvarchar, DecryptByKey(ClientCode, 1 , HashBytes('SHA1', CONVERT(varbinary, InstitutionID))))
FROM
dbo.lu_Institution
END
C# Code C#代码
public string Decrypt()
{
using (var cn = new SqlConnection(((EntityConnection) ObjectContext.Connection).StoreConnection.ConnectionString))
{
try
{
var sqlcmd = new SqlCommand("EXEC [dbo].[DecryptCCode]", cn);
sqlcmd.Parameters.Add("@decryptedStr", SqlDbType.NChar, 5);
sqlcmd.Parameters["@decryptedStr"].Direction = ParameterDirection.Output;
cn.Open();
sqlcmd.ExecuteNonQuery();
cn.Close();
return sqlcmd.Parameters["@decryptedStr"].Value != DBNull.Value ? (string)sqlcmd.Parameters["@decryptedStr"].Value : string.Empty;
}
catch (Exception e)
{
cn.Close();
Console.WriteLine(e.Message);
return string.Empty;
}
}
}
Your code looks fine, but you need to specify to the Command
the CommandType property, that the sql you are trying to execute is a Stored Procedure. 您的代码看起来不错,但是您需要向Command
指定CommandType属性,以使您尝试执行的sql是存储过程。
public string Decrypt()
{
using (var cn = new SqlConnection(((EntityConnection) ObjectContext.Connection).StoreConnection.ConnectionString))
{
try
{
cn.Open();
var sqlcmd = new SqlCommand("[dbo].[DecryptCCode]", cn);
// specify the command is a Stored Procedure
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.Add("@decryptedStr", SqlDbType.NChar, 5);
sqlcmd.Parameters["@decryptedStr"].Direction = ParameterDirection.Output;
sqlcmd.ExecuteNonQuery();
return sqlcmd.Parameters["@decryptedStr"].Value != DBNull.Value ? (string)sqlcmd.Parameters["@decryptedStr"].Value : string.Empty;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return string.Empty;
}
finally
{
cn.Close();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.