Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 cursor?

Author  Topic 

Movember
Starting Member

12 Posts

Posted - 2009-10-21 : 18:06:37

I am trying to update some records with a ID letter that are joined as a family. The primary member is marked as with 1 and they all have the same linkid and I am trying to give each member a unique letter like below. Not sure if this is possible?

i.e.

NAME LINKID PRIMARY ID
John Smith - 1234 - 1 - A
Joan Smith - 1234 - 0 - B
Tom Smith - 1234 - 0 - C

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2009-10-21 : 18:21:15
What version of SQL are you using? If 2005 or later, this should work for you:
-- Sample Data
DECLARE @MyTable TABLE(Name VARCHAR(50), LinkID INT, IsPrimary BIT, ID CHAR(1))
INSERT @MyTable
SELECT 'John Smith', 1234, 1, NULL
UNION ALL SELECT 'Joan Smith', 1234, 0, NULL
UNION ALL SELECT 'Tom Smith', 1234, 0, NULL
UNION ALL SELECT 'Frank Smith', 9234, 0, NULL
UNION ALL SELECT 'Bob Smith', 9234, 1, NULL

-- Run Upadate
UPDATE
T
SET
ID = CHAR(64 + RowNum)
FROM
(
SELECT
ID,
ROW_NUMBER() OVER (PARTITION BY LinkID ORDER BY IsPrimary DESC, Name) AS RowNum
FROM
@MyTable AS M
) AS T

-- Check update
SELECT *
FROM @MyTable
Go to Top of Page
   

- Advertisement -