COPY ONE TABLE TO ANOTHER IN SQL SERVER AUTOMATICALLY

Royce Roy

Total Post:149

Points:1043
Posted by  Royce Roy
C# 
C#
 1399  View(s)
Ratings:
Rate this:
Hello Guys

I have two tables in same database and I want to copy first table's data into second table automatically after some interval of time using c#.

Thanks!
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: copy one table to another in sql server automatically

    Hi Royce Roy!

    You can try this line of code

    Step 1. Used timer control as below code. For Timer control include System.Timers namespace

    timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
                timer1.Interval = 10000;
                timer1.Enabled = true;
                timer1.Start();

     

    2. Create Timer's Elapsed event and write code within this event for copy data from one table to another after 10 second (10000 mili seconds = 10 seconds)

     private void timer1_Elapsed(object sender, EventArgs e)
            {
                SqlConnection con = new SqlConnection("Data Source =  Your database service name; Initial Catalog = WindowsServiceDemo; User Id=  server ; Password= password;");
                SqlCommand cmd1;
                SqlCommand cmd2;
                SqlDataAdapter adap = new SqlDataAdapter("Select [EmpID],[EmpName] From [dbo].[EmployeeStatus] Where [IsActive]='False'", con);
                DataTable dt = new DataTable();
                adap.Fill(dt);
                con.Open();
                foreach (DataRow dr in dt.Rows)
                {
                    cmd1 = new SqlCommand("Insert into [dbo].[xEmployeeStatus]([EmpID],[EmpName]) values('" + dr[0].ToString() + "','" + dr[1].ToString() + "')", con);
                    if (cmd1.ExecuteNonQuery() > 0)
                    {
                        cmd2 = new SqlCommand("Update [dbo].[EmployeeStatus] Set [IsActive] = 'True' Where [IsActive]='False'", con);
                        int i = cmd2.ExecuteNonQuery();
                    }
                }
                con.Close();
                dt.Dispose();
                adap.Dispose();
            }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!