Home > DeveloperSection > Forums > Copy one table to another in sql server automatically
Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    January-17-2013 8:02 AM

 C# C# 
Ratings:


 1 Reply(s)
 1001  View(s)
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!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    January-29-2013 3:13 AM

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();
        }


Don't want to miss updates? Please click the below button!

Follow MindStick