user3085540
user3085540

Reputation: 295

Can i call the function in insert satement using c#

I am using the below code to insert data into a table. But i need the department value from database table.So i create a function in database and call this through the below code. I got the syntex error.

MySqlCommand InsertQueryToMysqlDB = new MySqlCommand("insert into employee(Employee_ID,Employee_Name,Department,Punchdate,Day,Intime) values('" + Empid + "','" + EmpName + "','fn_getdept('" + Empid + "')','" + PDate + "','" + Day + "','" + Time + "')", con);

Upvotes: 0

Views: 881

Answers (3)

user3624833
user3624833

Reputation:

Well, to make it simple... any query you can do in the SQLMMS, you can run from your C# ExecuteNonQuery.

Upvotes: 0

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

I guess there are can be some other mistakes too. You've put quotes everywhere. They should only surrond the non-numeric(string, datetime, guid, etc.) values.

Update: But if your function returns a non-numeric value you shouldn't surround it(the function call) with quotes since it will already be in quotes when returning from the function.

Example:

if your Empid is int it should be called like this:

"....values(" + Empid + ",...."

if your function returns string and gets int as parameter:

"....values(...., fn_getdept(" + Empid + "),...."

I hope you get the essence of quotes.

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66459

If you parameterize your queries, they'll be easier to maintain and you'll be less likely to run into issues with missing / extra / mismatched apostrophes.

var insertCommand = new MySqlCommand(
    "INSERT INTO employee(Employee_ID, Employee_Name, Department, Punchdate, Day, Intime) " +
    "VALUES(@Empid, @EmpName, fn_getdept(@Empid), @PDate, @Day, @Time)", con);

insertCommand.Parameters.AddWithValue("@Empid", Empid);
insertCommand.Parameters.AddWithValue("@EmpName", EmpName);
insertCommand.Parameters.AddWithValue("@PDate", PDate);
insertCommand.Parameters.AddWithValue("@Day", Day);
insertCommand.Parameters.AddWithValue("@Time", Time);

Upvotes: 1

Related Questions