隨着下面的存儲過程在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