Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing FieldName as Parameter in MySQL Stored Procedure

Tags:

mysql

I am passing table field name as parameter to stored procedure but stored procedure take field name as value instead of field name and throws error.

e.g if i pass value isEnabled via parameter FieldName, Mysql throws error unknown column 'isEnabled' in field list, which shows mysql automatically add quote.

Here is sample stored procedure i wrote.

CREATE `VSK_Comments_UpdateAction`(IN FieldName varchar(30),IN FieldValue tinyint,CID bigint)
BEGIN
Update comments Set FieldName=FieldValue WHERE commentid=CID;
END;

Is there is a way so i can properly pass field name dynamically properly.

like image 375
irfanmcsd Avatar asked Apr 03 '12 13:04

irfanmcsd


People also ask

Can I pass column name as input parameter in SQL stored procedure?

You can do this in a couple of ways. One, is to build up the query yourself and execute it. If you opt for that method, be very certain to santise your input.

Can we pass Datatable to a stored procedure in MySQL?

Create a user-defined table type that corresponds to the table that you want to populate. Pass the user-defined table to the stored procedure as a parameter. Inside the stored procedure, select the data from the passed parameter and insert it into the table that you want to populate.

Can we pass array to stored procedure in MySQL?

MySQL Stored Procedures do not provide an array data type. You could implode the php array to a separated string and pass this string as VARCHAR(255) to the stored procedure. Inside the procedure you could split this string back into its elements (see example below).


1 Answers

You can use prepared statements, for example -

CREATE `VSK_Comments_UpdateAction`(IN FieldName varchar(30),IN FieldValue tinyint,CID bigint)
BEGIN
  SET @query = CONCAT('Update comments Set ', FieldName, '=? WHERE commentid=?');
  PREPARE stmt FROM @query;
  SET @FieldValue = FieldValue;
  SET @CID = CID;
  EXECUTE stmt USING @FieldValue, @CID;
  DEALLOCATE PREPARE stmt;
END;
like image 59
Devart Avatar answered Oct 31 '22 20:10

Devart