Duplicate Transaction

Duplicate a Record in MySql Table with Auto Increment Key

I have worked with MySql for several years now, and there have been cases where I needed to copy (or duplicate) in a table where an auto-increment key exists.
The following function for VB.NET is a solution that has been helping me a lot recently.
So, I decided to share it with you all!

This is a public static Boolean function and you can call it from your code: 

    public static bool copy_recod(string tbl, string tbl_id_name, long tbl_id_value)
{
	string dup_query = null;
	DataTable tbl_dat = new DataTable();
	long next_id = 0;
	string copy_query = null;
	string col_value = null;
	
	bool did_it = false;
	
	dup_query = "select * from " + tbl + "         where " 
		+ tbl_id_name + "=" + System.Convert.ToString(tbl_id_value);
	tbl_dat = retriveDataToDataGrid(dup_query);
	
	if (!ReferenceEquals(tbl_dat, null))
	{
		ActionRecord("LOCK TABLES " + tbl + " WRITE");
		ActionRecord("insert into " + tbl + 
			"(" + tbl_id_name + ")values( NULL)");
		
		next_id = (long) (Val(get_single_field(@"select MAX_
(" + tbl_id_name + ") from " + tbl, 0)));
		
		ActionRecord("UNLOCK TABLES");
		
		copy_query = "update " + tbl + " set ";
		foreach (DataRow r in tbl_dat.Rows)
		{
			foreach (DataColumn col in tbl_dat.Columns)
			{
				
				if (col.ColumnName != tbl_id_name)
				{
					col_value = r[col].ToString();
					
					if (col.DataType.ToString().ToString().IndexOf("String") + 1 > 
						0 || col.DataType.ToString().ToString().IndexOf("Date") + 1 > 0)
					{
						copy_query = copy_query + col.ColumnName + 
							"='" + col_value + "',";
					}
					else
					{
						
						if (Information.IsDBNull(col_value) || col_value.Length <= 0)
						{
							col_value = "0";
						}
						
						
						copy_query = copy_query + col.ColumnName + "=" + col_value + ",";
					}
					
				}
				
			}
		}
		
		copy_query = copy_query.Remove(copy_query.LastIndexOf(","), 1);
		
		if (copy_query.Substring(copy_query.Length - 1, 1) == "=")
		{
			copy_query = copy_query + "'" + System.Convert.ToString(0) + "'";
		}
		
		copy_query = copy_query + " where " + tbl_id_name + "=" + System.Convert.ToString(next_id);
		if (ActionRecord(copy_query) > 0)
		{
			did_it = true;
		}
	}
	
	return did_it;

For me to create this open function that could work for any table, regardless of the number of fields, I had to use enough variables and have checkpoints to assure a clean and workable code.
The critical part of this code is where it recognizes the field type and creates proper SQL command for the copy.
ActionRecord() function is my function to run a query. So you can change that with your code to launch the update query.

Kourosh

Your Header Sidebar area is currently empty. Hurry up and add some widgets.