Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add a NewID using several columns to define distinct records 1

Status
Not open for further replies.

SDB15

Technical User
Apr 9, 2009
21
US
I have imported some data from excel spreadsheets where a person may pop up multiple times over the years of data I am working with. I want to assign an ID to them by using newid. How do I insert the new column and get SQL to assign the same ID to the same person even though there are different occurances?
 
Using SQL Server 2005 and up is very easy

select * into myNewTable from (select *, row_Number() over (partition by PersonName) as IdField from myCurrentTable) X
 
That makes sense, thanks! Now how do I add more than one criteria to the partition?
 
Just separate them with command, e.g.

partition by PersonName, PersonAddress1, etc.
 
Comma, not command - sorry, I'm almost ready to leave now.
 
Got it. Thanks again for your help.
 
Ran into some problems here is my code:
Code:
select * into Republicans_2 from (select *, row_Number() 
over (partition by 
LName,
FName,
Addr1,
City,
Zip) 
as IdField from Republicans) X

I get this message: "The ranking function "row_Number" must have an ORDER BY clause."

And where do I specify the newid command? Will this create a string of characters like
Code:
CAST(Replace(NewID(),'-','') AS Varchar(32))
?
 
Code:
select Republicans.*, Tbl1.New_Id
       into Republicans_2
from Republicans
INNER JOIN (SELECT LName,
                   FName,
                   Addr1,
                   City,
                   Zip,
                   MAX(CAST(Replace(NewID(),'-','') AS Varchar(32))) AS New_Id
            FROM Republicans
            GROUP BY LName, FName, Addr1, City, Zip) Tbl1
ON Republicans.LName = Tbl1.LName
   Republicans.FName = Tbl1.FName
   Republicans.Addr1 = Tbl1.Addr1
   Republicans.City  = Tbl1.City
   Republicans.Zip   = Tbl1.Zip
NOT TESTED!!!

Borislav Borissov
VFP9 SP2, SQL Server 2000/2005.
 
You can add ORDER BY any column into the OVER (...) clause.

If you want your newID to be a GUID field and not an integer, I guess you can add an extra field to your table
and then to UPDATE using self-join.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top