views:

40

answers:

2

Hi,

I have an SQL (Microsoft SQL 2008) table with XML data in one of the columns. Each XML root node has an attribute which is a GUID.

For example:

<!--Row 1-->
<example:root id="E0B1BCEA-C0E2-4d7c-BF67-FA9A7C3FBA73">
    [...]
</example:root>

<!--Row 2-->
<example:root id="13BB87F4-32A5-4de7-8CE9-E62AF002B958">
    [...]
</example:root>

How is it possible to create a constraint which will ensure that this GUID is unique, i.e. there is no two rows sharing the same root/@id value?

Note: I can't neither do it at application level, nor creating a stored procedure for the insert (because it requires to change an existing application).

+1  A: 

If it is not a separate field then I don't think you can.

But, you can add a trigger on insert which would extract GUID from the XML data and put it in a separate field. And then you can have a unique constraint on that field.

Another approach would be to create a nightly job, which would scan the database in search of duplicates.

z-boss
+2  A: 

Yes, you could

  • write a stored function that extracts the "id" from the XML
  • create a computed, persisted column on your table which grabs that "id" using that stored function
  • create a unique index on your new, computed + persisted column

That would definitely work.

marc_s
+1, exactly what I was thinking!
KM