Question

I have a table containing a list of MAC addresses that in some cases has been padded to twelve digits and in other cases has not.

ie: 00FF12345678 OR FF12345678

There are cases where both values exist in this table. I have a function that pads the value with the two zeroes and I can count the occurrence of these duplicates, but I don't have the time or patience to manually remove the duplicates or pad those that do not already have a record.

I figured I could update the 10 digit values to their correct value with the following statement:

UPDATE [rs_DEVICES]
SET [device] = dbo.pad_zero(12,[device])
WHERE LEN([device]) < 12

Of course this doesn't work because I need to only update those values that do not have an existing 12 digit record. The unique constraint on this column stops me from doing this.

I need some sort of IF EXISTS statement in the WHERE clause but I haven't been able to come up with anything that works.

Using MSSQL Server 2008 R2.

Thoughts?

Was it helpful?

Solution

This does the job for you:

UPDATE [rs_DEVICES]
SET [device] = dbo.pad_zero(12,[device])
WHERE LEN([device]) < 12 AND NOT EXISTS (
    SELECT 1 FROM rs_DEVICES r1 WHERE r1.device = dbo.pad_zero(12,[device])
)

I think it's self explanatory, but if you have any questions please comment.

Honestly though, I recommend you to fix the real problem. Reassign the current references to the length=10 records to their respective length=12 siblings and then remove them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top