随着下面的存储过程在SQL Server 2005中从C#中的存储过程,需要一个返回值
IF OBJECT_ID('[dbo].[UserProfile]') IS NOT NULL
DROP PROCEDURE [dbo].[UserProfile]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[UserProfile]
(
@UserId VARCHAR(20)
)
AS
IF @UserId = 'userId'
BEGIN
SELECT @UserId = 'Yes'
END
ELSE
SELECT @UserId = 'No'
SELECT @UserId AS RESULT
RETURN RESULT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
C#代码,需要获取存储过程的结果
public String UserProfile(string userId)
{
String result;
System.Data.Common.DbCommand cmd = this.mConn.CreateCommand();
try
{
cmd.CommandTimeout = this.mCmdTimeout;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UserProfile";
DbParameter p = cmd.CreateParameter();
p.ParameterName = "@UserId";
p.DbType = DbType.String;
p.Value = userId;
cmd.Parameters.Add(p);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
//Need to assign the value of the stored procedure's return to result
result = Convert.ToString(cmd.Parameters["@UserId"].Value);
}
catch (Exception ex)
{
throw;
}
finally
{
cmd.Connection.Close();
}
return result;
}
如何在C#中返回我的存储过程的结果?
简单的东西,这就是我一直在寻找。你也必须转换为你想要的类型,在这种情况下它是一个字符串。 – 2009-10-28 14:55:04
是的,这是迄今为止最简单的答案。 – 2009-10-28 14:58:12
此方法不适用于具有返回值而不是返回的输出值或行的存储过程。有关返回值,请参阅user_v的答案。 – Josh 2015-04-30 15:59:16