Question : Update field following DISTINCT query

Okay I have imported some data into a table in SQL 2005 and I have a simple query that I run against it:

SELECT DISTINCT Business_Migration_Ref, OrgNm, AddrLn1, AddrLn2, AddrLn3, AddrLn4, AddrPostCd
FROM         InitialData
WHERE     (OrgNm IS NOT NULL) AND (LEN(OrgNm) > 0) AND (Business_Migration_Ref IS NULL)

This query produces about 2500 records from my table.

What I need to do is to add a unique reference to the 2500 records under the Business_Migration_Ref field. Presently this field is blank but I need to add something unique to it so that I can reference it somehow.

Now I can use my statement above to query the table no problem but how would I go about adding or enhancing it so that it could find the records and then update each one with a unique reference number?

I've created a seperate table using another query:

SELECT DISTINCT IDENTITY (int,500000,1) AS Business_Migration_Ref, OrgNm, AddrLn1, AddrLn2, AddrLn3, AddrLn4, AddrPostCd
INTO NewTableName
FROM         InitialData
WHERE     (OrgNm IS NOT NULL) AND (LEN(OrgNm) > 0) AND (Business_Migration_Ref IS NULL)

and this works beautifully and gives me my DISTINCT records no problem but I'd need to match these back to the original InitialData table somehow (and this could potentially mean checking about 6 fields to determine the uniqueness of a record).

Is there a way for me to query my original table (InitialData) and update DISTINCT Business_Migration_Ref numbers in some way so that I do not lose any of my data? Not sure if I need to create a temp table in some way (like by using my second query above) and then using this as a possible referencing table for the original one.

I know this looks complex but I don;t think it is but I'm not sure if I'm putting my logic across correctly.

Thanx for any advice anyone can offer.

Answer : Update field following DISTINCT query

This is probably because some of the fields joined have null values

Try
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
UPDATE I
SET Business_Migration_Ref = T.rn
FROM
  InitialData I INNER JOIN
  (SELECT DISTINCT
     OrgNm, AddrLn1, AddrLn2, AddrLn3, AddrLn4, AddrPostCd
    ,rn = dense_rank() over(order by OrgNm, AddrLn1, AddrLn2, AddrLn3, AddrLn4, AddrPostCd)
   FROM InitialData
   WHERE OrgNm IS NOT NULL AND LEN(OrgNm) > 0 AND (Business_Migration_Ref IS NULL)
  ) T ON (I.OrgNm=T.OrgNm OR (I.OrgNm IS NULL AND T.OrgNm IS NULL)) AND
         (I.AddrLn1=T.AddrLn1 OR (I.AddrLn1 IS NULL AND T.AddrLn1 IS NULL)) AND
         (I.AddrLn2=T.AddrLn2 OR (I.AddrLn2 IS NULL AND T.AddrLn2 IS NULL)) AND
         (I.AddrLn3=T.AddrLn3 OR (I.AddrLn3 IS NULL AND T.AddrLn3 IS NULL)) AND
         (I.AddrLn4=T.AddrLn4 OR (I.AddrLn4 IS NULL AND T.AddrLn4 IS NULL)) AND
         (I.AddrPostCd=T.AddrPostCd OR (I.AddrPostCd IS NULL AND T.AddrPostCd IS NULL))
Random Solutions  
 
programming4us programming4us