1

I'm moving my stored procedures to C# code. In the stored procedures I have something like

Begin
SET @Id = null;
IF ?Status = 0 THEN SET ? ?DateToday = UTC_TIMESTAMP(); END IF;
SELECT * FROM TABLE
END 

In the C# Code I just copy pasted everything inside Begin and END. Like so,

MySqlCommand command = new MySqlCommand();
command.CommandText = @"SET @Id = null;
IF ?Status = 0 THEN SET ? ?DateToday = UTC_TIMESTAMP(); END IF;
SELECT * FROM TABLE"

I have an error in the If statement saying incorrect syntax. The stored procedure is working but not when I place it in C# code.

4
  • Why not use only command.CommandText = "SELECT * FROM TABLE" Commented Nov 14, 2016 at 6:57
  • Does your stored procedure have parameters? Commented Nov 14, 2016 at 6:57
  • @Damith its just an example, the Set and If statement are causing errors. Commented Nov 14, 2016 at 7:02
  • @BlackFrog yes it does. i've set it in the code too. Commented Nov 14, 2016 at 7:02

2 Answers 2

1

That's not the logic of Stored Procedures. As its name implies stored procedures are functions that are stored in the database itself. And you can invoke them by calling their names.

Hence you cannot just put the stored procedure function code in your C# code, I mean you shouldn't.

Update: If you only want to use T-SQL statements (if-else blocks and so) check out this link.

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

1 Comment

I understand, but what is the counterpart of Set and the If statement in C# CommandText?btw thanks for you reply :)
0

If you have created a stored procedure then you can call it using a stored procedure syntax like this;

using (SqlConnection con = new SqlConnection(someconnectionstring)) {
    using (SqlCommand cmd = new SqlCommand("myStoredProc", con)) {
      cmd.CommandType = CommandType.StoredProcedure;
      //If you have parameters in your SP, add like this else ignore below line
      cmd.Parameters.Add("@myparam", SqlDbType.VarChar).Value = somevalue;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }

1 Comment

@Cosytyle;- Any specific reason to do that. As it is not a good coding practice?

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.