Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy data to and from the same table and change the value of copied data in one column to a specified value

Tags:

I want to copy some data in a single table in a SQL Server 2008 database and copy it into the same table and change the values in one column of the copied data to a single specified number. Here is an example, in the following table called Metric, the data is:

Key  Name    MetricValue 112    Joe      34 112    Fred     38 112    Frank    12 112    John     56 112    David    87 112    Sue      43 234    Alli     34 234    Susan    38 234    Anne     12 234    Franki   56 

I want to copy all those entries with a key of 112 to Metric and assign all copied rows a Key of 387, this gives the values in the table Metric as:

Key  Name    MetricValue 112    Joe      34 112    Fred     38 112    Frank    12 112    John     56 112    David    87 112    Sue      43 234    Alli     34 234    Susan    38 234    Anne     12 234    Franki   56 387    Joe      34 387    Fred     38 387    Frank    12 387    John     56 387    David    87 387    Sue      43  

Note, this table also has a primary key which I have not shown above.

How can I do this in SQL that is compatible with SQL Server 2008.

Thanks for the help,

Tony

like image 729
flyhai Avatar asked Feb 10 '12 08:02

flyhai


People also ask

How do I copy data into the same table based on existing data in SQL?

If you want to copy the data of one SQL table into another SQL table in the same SQL server, then it is possible by using the SELECT INTO statement in SQL. The SELECT INTO statement in Structured Query Language copies the content from one existing table into the new table.

How can we UPDATE one column value from another column in the same table?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

How do I replicate data from one table to another?

To copy column definitions from one table to another. Open the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design. Click the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy.


1 Answers

Here you try..

INSERT INTO Metric(Key,Name,MetricValue) SELECT 387,Name,MetricValue FROM Metric WHERE Key = 112 
like image 182
Thit Lwin Oo Avatar answered Oct 20 '22 16:10

Thit Lwin Oo