1

I am using ASP.NET MVC, SQL database with model and entity. I wrote a SQL function in the database, and C# code in controller. I am trying to call a SQL function with C# and store SQL function returned int to C# int variable. And I have trouble time trying to work it.

I wrote the test code so when I know what to do, I can use this knowledge to resolve the problem I'm having.

I've tried researching, but none of the answers helped so far.

SQL Code:

CREATE FUNCTION dbo.TestFunction(@Number INT)
RETURNS INTEGER
AS 
BEGIN
    IF (@Number = 1)
    BEGIN
        RETURN 45
    END

    RETURN 20
END

C# code:

using (websiteDBEntities d = new websiteDBEntities())
{
    int check = d.Database.ExecuteSqlCommand("SELECT dbo.TestFunction(1)");

    if (check == 45)
         return RedirectToAction("Action", "Controller");
}

return RedirectToAction("Action 2", "Controller");

I am trying to return either 20 or 45 depending on a parameter value.

So, is there a proper way to store a SQL function returned value to C# variable?

2 Answers 2

2

Try d.Database.SqlQuery() - it returns IEnumerable of result data set. It seems that ExecuteSqlCommand() returns number of rows modified.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sooo much. It worked. I changed my code to: var check = d.Database.SqlQuery<int>("SELECT dbo.TestFunction(1)"); if(check.Sum() == 45) return RedirectToAction("Action", "Controller");
0

Your function in the second line says that the function returns a bit value and you are returning an int. You should change returns bit to returns int.

1 Comment

My bad, I meant Integer. I changed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.