Unique XML element constraint in T-SQL
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">
[...]
</exa开发者_开发知识库mple: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).
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.
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.
精彩评论