Search code examples
mysqlstored-proceduressql-function

Create procedure/function working for different tables in MySQL


As far as I know, there is no possibility in MySQL to pass a table handle. So the question is how to write a procedure/function that works for different tables. Is it neccessary to hardcode table names in every proc/fun? Let's say I want to doSomethingWithTable(...) and am I forced to create one for every table even if it's exactly the same operation? Do I really need to create X times same proc/fun changing only its name (doSomethingWithTableClients(...), doSomethingWithTableUsers(...), doSomethingWithTableItems(...) and so on)?


Solution

  • You can to pass the table name as variable use dynamic SQL to perform whatever you wish to do.

    It's actually quite rare that you would do same things on all tables in a procedure. Things like changing charcter sets / collations come to mind but usually in procedures there is logic involved and that logic differs from table to table.