SQL: inserts data from one table into another table to eliminate duplicate data.

Source: Internet
Author: User

Now there are two tables to insert data in Table A into Table B. They all have three fields, and the fields in Table A do not have a primary key, and there are also repeated data fields, however, this field in Table B does not need to be repeated and must be unique. At this time, I thought of a simple and fast way to use the cursor to read data from one row and one row, insert the read data into a temporary table. In the temporary table, I set a self-increasing ID so that the duplicate can be eliminated through the same ID (that is, through the maximum or minimum ID method)CodeExample:

Select * From declare @ icard varchar (20)
Declare @ num varchar (20)
Declare @ intid varchar (20)
Declare @ newtable table (ID int identity (1, 1), icard varchar (20), INAME varchar (20), iage varchar (20 ))
Select Identity (INT, 1, 1) as ID, * into newtable from
Declare cursor_xs cursor
Select icard, INAME, iage from newtable where ID in (select max (ID) from newtable group by [icard])
Open cursor_xs
Fetch next from cursor_xs into @ icard, @ num, @ intid
While @ fetch_status = 0
Begin
Insert into B values (@ icard, @ num, @ intid)
Fetch next from cursor_xs into @ icard, @ num, @ intid
End
Close cursor_xs
Deallocate cursor_xs
Drop table newtable

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.