[英]Failed to get result of stored procedure
I created a procedure that returns the ID of the Question based on the input text 我创建了一个根据输入文本返回问题ID的过程
ALTER PROCEDURE [dbo].[GetQuestionIDbyTekst]
(
@Tekst nvarchar(100)
)
AS
DECLARE @QuestionID int
SELECT QuestionID
FROM dbo.Questions
WHERE Tekst = @Tekst
RETURN @QuestionID
and I have a problem in getting the value of the QuestionID
: 我在获取QuestionID
的值时遇到QuestionID
:
public static int getQuestionID(Question p)
{
using (Entities dm = new Entities())
{
return dm.GetQuestionIDbyTekst(p.Tekst);
}
}
Make the @QuestionID
as Output
parameter. 将@QuestionID
为Output
参数。 Also you need to assign the result to @QuestionID
另外,您需要将结果分配给@QuestionID
ALTER PROCEDURE [dbo].[GetQuestionIDbyTekst]
(
@Tekst nvarchar(100),
@QuestionID INT OUTPUT
)
AS
BEGIN
DECLARE @QuestionID int
SELECT @QuestionID = QuestionID FROM dbo.Questions WHERE Tekst = @Tekst
END
please try this: 请尝试以下操作:
ALTER PROCEDURE [dbo].[GetQuestionIDbyTekst]
(
@Tekst nvarchar(100)
)
AS
-- DECLARE @QuestionID int
SELECT QuestionID
FROM dbo.Questions
WHERE Tekst = @Tekst
-- RETURN @QuestionID
You can use your variant of the stored procedure. 您可以使用存储过程的变体。
And if you use ADO.NET and want to get return value, try this: 如果您使用ADO.NET并希望获得返回值,请尝试以下操作:
SqlConnection con = new SqlConnection(@"Data Source=localhost\***;Initial Catalog=***;Integrated Security=True;Persist Security Info=False;");
con.Open();
SqlCommand cmd = new SqlCommand("GetQuestionIDbyTekst", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("@Tekst", System.Data.SqlDbType.NVarChar).Value = "eee";
SqlParameter returnPar = new SqlParameter();
returnPar.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(retturnPar);
cmd.ExecuteScalar();
var result = returnPar.Value;
If you use Entity Framework, you may use this variant: 如果使用实体框架,则可以使用以下变体:
public static int GetQuestionIDbyTekst(string question)
{
using (var context = new EfDbContext())
{
var test = new SqlParameter("@Tekst", question);
var resultParam = new SqlParameter("@result", SqlDbType.Int);
resultParam.Direction = ParameterDirection.Output;
context.Database.ExecuteSqlCommand("exec @result = [dbo].[testProc] @Tekst", resultParam, test);
return (int)resultParam.Value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.