Last updated on 7th October 2016
Extended Properties in SQL Server
With SQL Server, it is strange how some of the most radical improvements that have been introduced over the years have been slipped in almost unnoticed. Conversely, the features that were plastered all over the marketing brochures are sometimes the ones that turn out to be dead ends.
A feature that fits into the former category is the extended properties of databases. Introduced quietly with SQL Server 2000, one could have easily missed them but they have proved, after all, to be of great value to the developer. Extended properties are the route to creating self-documenting databases. I use the term ‘self-documenting’ in the sense that one can attach the documentation directly to the database itself and its objects, rather than create a separate document. Basically, you use the extended properties of data objects to apply your own properties to the metadata.
Using extended properties
The classic example is to use extended properties of an object to append a description of that object, be it a trigger, stored procedure, function, table, view, parameter, index, constraint or column. One can also use extended properties to document details such as the date of revision, author, input mask, caption, history, rendering-style, and so on.
One of the classic general tricks that programmers have used in the past to add documentation to source code is to structure the comments of source code by inserting predefined markers to indicate the category of information (revision date, for example) to any application that generates the documentation (such as Javadocs). This can’t be done in SQL Server as source is only maintained in the database for certain objects such as procedures and functions. Since the introduction of extended properties, such tricks would be unnecessary anyway.
The advantage of using the extended properties is that the documentation, notes, and so on stay with the databases and can be used as a “live documentation” mechanism. They are backed up with the database, and scripted out with the build scripts.
Despite their obvious utility, Microsoft has treated the feature with a curious lack of enthusiasm. There is the smell of ‘wet paint’ about the design. Extended properties allow you to document your database objects but it has been left to third-party utilities such as SQL Doc and DBDesc to exploit the use of these properties for generating the full documentation of the database from the database itself.
A consequence of Microsoft’s indifference to extended properties is that they forgot to include them in the replication synchronisation process. You have to do it manually (a tool such as SQL Compare will synchronise them properly). Also, they neglected to provide an Information_Schema view of the extended properties, which would have made to make it easier to access them from SQL.
Another difficulty is that some third-party software vendors have used the extended properties for other purposes, such as storing parameters for entity-relationship diagrams. This makes it difficult for utilities that extract the documentation as there is no standard property name other than MS_Description.
Creating extended properties via code
Microsoft provides one extended property, MS_Description, which can be used from both Enterprise Manager and SSMS to provide a description of the object to which it is bound. Further, the Diagram Designer provides a description field, accessible via the custom view, which provides an easy way of viewing and editing the documentation of the columns.
However, extended properties are just about providing basic descriptions of objects. They are a lot more versatile that that. The designers of extended properties sensibly placed no restrictions on the properties that one could attribute to database objects. It is perfectly OK, for example, to provide extra metadata to assist the application layer in rendering or querying the data.
When writing the documentation for objects, it is generally quickest to use the facilities within Microsoft’s own tools to add basic descriptions, but beyond that there eventually comes a time that one has to use stored procedures to add documentation.
At the basic level, in SQL Server 2000, all extended properties are stored in sysproperties, but are accessed by a number of stored procedures.
sp_addextendedproperty |
Adds a new extended property to a database object |
sp_dropextendedproperty |
Removes an extended property from a database object |
sp_updateextendedproperty |
Updates the value of an existing extended property |
fn_listextendedproperty |
Retrieves the value of an extended property or the list of all extended properties from a database object |
These stored procedures are clumsy to use and hardly encourage the programmer into using extended properties. However, a few examples might make their use a bit clearer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/*we add the extended property to provide a description to the dbo.Customer.InsertionDate column */ EXECUTE sys.sp_addextendedproperty 'MS_Description', 'the date at which the row was created', 'schema', 'dbo', 'table', 'Customer', 'column', 'InsertionDate'; -- alternative syntax for SQL 2005 EXECUTE sys.sp_addextendedproperty 'MS_Description', 'the date at which the row was created', 'schema', 'sales', 'table', 'Customer', 'column', 'ModifiedDate'; /* and then update the description of the dbo.Customer.InsertionDate column */ EXECUTE sys.sp_updateextendedproperty 'MS_Description', 'the full date at which the row was created', 'schema', 'dbo', 'table', 'Customer', 'column', 'InsertionDate'; /* we can list this column */ SELECT * FROM::fn_listextendedproperty('MS_Description', 'schema', 'dbo', 'table', 'Customer', 'column', 'InsertionDate'); /* or all the properties for the table column of dbo.Customer*/ SELECT * FROM::fn_listextendedproperty(DEFAULT, 'schema', 'dbo', 'table', 'Customer', 'column', DEFAULT); /* And now we drop the MS_Description property of dbo.Customer.InsertionDate column */ EXECUTE sys.sp_dropextendedproperty 'MS_Description', 'schema', 'dbo', 'table', 'Customer', 'column', 'InsertionDate'; |
A database-documenting stored procedure
I find the stored procedures described in the previous section unintuitive and don’t exactly tempt the programmer into adding documentation. For a start, if you try to add an extended property that already exists, you get an error. If you update an extended property that doesn’t exist, you get an error. If you put an extended property on an object that doesn’t exist, you get no error or return code to tell you. From SQL Server 2005 onwards, a system view was added to make it easier to read extended properties but this doesn’t help with adding, deleting or updating them. I’d prefer something that described the object and its hierarchy in a more conventional way. For example if one wanted to alter the description of a surname column in a Customer table then it should be ‘dbo.Customer.Surname.MS_Description‘ using the ‘schema.table.column‘ hierarchy.
In order to make things easier, I created a simple ‘helper’ stored procedure which simplifies the access to Microsoft’s system stored procedures, but doesn’t try to replace them. If you provide the description of the object and the hierarchy, then it displays what is there. If you provide a value, it either assigns it or, if you want, appends it to the end of the current value.
The stored procedure autosenses which version of SQL Server it is on, and loads with the valid object hierarchies for the operating system. It checks the hierarchy you give it to see if it is valid. This list is rather handy, so the stored procedure also includes a feature that provides the hierarchy as a table.
The full source code for this sp_DBDoc stored procedure is provided in the source code for this article. It is designed to reside in the MASTER database so it can be used as a utility in any database on the server, but you must be db_owner in any database you want to use it for.
Create the stored procedure and let’s try it out. First, let’s see what hierarchies can have extended properties:
1 |
EXEC sp_DbDoc '','','','possible' |
or, alternatively:
1 |
sp_DbDoc @Function='possible' |
You will see that there are rather a lot – and that the possible objects that can have attributes attached to them were greatly expanded in SQL 2005, and just four were added since (those picked out in bold are available in both 2000 and 2005, but ‘user’ became ‘schema’ from 2005 onwards):
assembly |
Schema.Service |
user.function.Constraint |
contract |
Schema.Synonym |
user.function.Parameter |
Event Notification |
Schema.Table |
user.Procedure |
fileGroup.Logical file Name |
Schema.Table.Column |
user.Procedure.Parameter |
Message type |
Schema.Table.Constraint |
user.Queue |
partition Function |
Schema.Table.Index |
user.Queue.Event Notification |
partition Scheme |
Schema.Table.Trigger |
User.Rule |
Remote Service Binding |
Schema.Type |
user.Service |
route |
Schema.View |
user.Synonym |
Schema |
Schema.View.Trigger |
User.Table |
schema.aggregate |
Schema.View.column |
User.Table.Column |
schema.Default |
Schema.View.index |
User.Table.Constraint |
schema.function |
Schema.XML Schema Collection |
User.Table.Index |
schema.function.column |
Service |
User.Table.Trigger |
schema.function.Constraint |
trigger |
user.Type |
schema.function.Parameter |
type |
User.View |
schema.Procedure |
user |
User.View.column |
schema.Procedure.Parameter |
user.aggregate |
User.View.index |
schema.Queue |
user.Default |
User.View.Trigger |
schema.Queue.Event Notification |
user.function |
User.XML Schema Collection |
schema.Rule |
user.function.column |
Asymmetric Key |
Certificate |
Plan guide |
Synonym |
Let’s start very simply. Let’s just create a description for the entire database:
1 |
EXEC sp_dbDoc '','','This is a sample database that illustrates how extended properties can be assigned to objects' |
Nothing exciting here so let’s add a ‘revision date’ property:
1 |
EXEC sp_dbDoc '','revisionDate','20 Nov 2006: Built the first iteration' |
Now we want to add the new version, rather than replace the existing value:
1 |
EXEC sp_dbDoc '','revisionDate','21 Nov 2006: Fixed warning message in build script','append' |
We can list all extended properties and values for columns of a given table, for example the customer table:
1 |
EXEC sp_dbDoc 'user.table.column','dbo.customer' -- SQL 2000 EXEC sp_dbDoc 'schema.table.column','sales.customer' -- alternative in SQL 2005 onwards |
Assigning a standard MS_Documentation property and value is easy:
1 |
/* either alter or create an entry for the MS_Documentation property for insertionDate */sp_dbDoc 'user.table.column','dbo.customer.insertionDate','This logs the date that the row was inserted' |
Or you can add your own property. By way of example, we assign a suggested convert style for a date field:
1 |
/* either alter or create an entry for the ConvertStyle property for insertionDate */ EXEC sp_dbDoc 'user.table.column','dbo.customer.insertionDate.ConvertStyle',113 |
In the following code you’ll find several more examples for this procedure included as comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
USE master; IF EXISTS (SELECT 1 FROM sys.objects WHERE objects.name = 'sp_DbDoc') DROP PROCEDURE sp_DBDoc; GO CREATE PROCEDURE sp_DBDoc @hierarchy VARCHAR(40) = '', @object VARCHAR(40) = '', @value SQL_VARIANT = NULL, --'This column tells you the date of insertion', @Function VARCHAR(20) = 'assign' /* --lists all extended properties and values for columns of the 'customer' table. sp_DbDoc 'schema.table.column','person.person' sp_DbDoc '','','This database is for testing purposes only' --specify the default Extended property sp_DbDoc '','','','delete' --delete the MS_Description Extended property sp_DbDoc '','','','possible' --list out all possible hierarchies supporting EPs --or sp_DbDoc @Function='possible'--list out all possible hierarchies supporting EPs --lists all extended properties and values for columns of the 'customer' table. sp_DbDoc 'schema.table.column','person.contactType'--error on SQL Server 2000 --either alter or create an entry for the MS_Documentation property for insertionDate sp_DbDoc 'user.table.column','dbo.customer.insertionDate','This logs the date that the row was inserted' --either alter or create an entry for the ConvertStyle property for insertionDate sp_DbDoc 'schema.table.column','dbo.customer.insertionDate.ConvertStyle',113 --either alter or create an entry for the MS_Documentation property for title sp_DbDoc 'schema.table.column','dbo.customer.title','e.g. Mr Mrs, Madame, sir, etc' --either alter or create an entry for the 'Range' property for DOB sp_DbDoc 'schema.table.column','dbo.customer.DOB.range','01 Jan 1920' sp_DbDoc 'schema.procedure','dbo.spGetCustomer', 'This procedure gets the documentation ' sp_DbDoc 'schema.procedure.parameter','dbo.spGetCustomer.@customer_ID', 'This is the ID of the customer' --create a description for the database sp_DbDoc '','','This is a sample database that illustrates how extended properties can be assigned to objects' Execute sp_DbDoc 'Database','version','3.2.2 (removed incomprehensible CTEs)','append' --add a new property called 'revision date' sp_DbDoc '','revisionDate','20 Nov 2006' --append to the value string in the property 'revision date' sp_DbDoc '','revisionDate','-Fixed warning message (21 Nov 2006)','append' */ AS DECLARE @Hits INT; DECLARE @Level0 VARCHAR(40); DECLARE @Level1 VARCHAR(40); DECLARE @Level2 VARCHAR(40); DECLARE @Name0 VARCHAR(40); DECLARE @Name1 VARCHAR(40); DECLARE @Name2 VARCHAR(40); DECLARE @ErrorMessage VARCHAR(40); DECLARE @LowestVersion INT; DECLARE @HighestVersion INT; DECLARE @V9 INT; DECLARE @Split INT; DECLARE @Split2 INT; DECLARE @Split3 INT; DECLARE @Property VARCHAR(80); DECLARE @PropertyForAmendment VARCHAR(80); DECLARE @SQLVersion INT; DECLARE @Return INT; DECLARE @Database VARCHAR(40); SET NOCOUNT ON; SELECT @Return = 0, @Database = DB_NAME(); IF @hierarchy = 'Database' SELECT @hierarchy = ''; DECLARE @hierarchies TABLE ( Hierarchy VARCHAR(40) UNIQUE, Level0 VARCHAR(40), Level1 VARCHAR(40), Level2 VARCHAR(40), LowestVersion INT, HighestVersion INT ); INSERT INTO @hierarchies SELECT TheHierarchies.Hierarchy, TheHierarchies.Level0, TheHierarchies.Level1, TheHierarchies.Level2, TheHierarchies.LowestVersion, TheHierarchies.HighestVersion FROM ( VALUES('', NULL, NULL, NULL, 8, NULL), --database ('Asymmetric Key', 'Asymmetric Key', NULL, NULL, 10, NULL), ('Certificate', 'Certificate', NULL, NULL, 10, NULL), ('Plan guide', 'plan guide', NULL, NULL, 10, NULL), ('Synonym', 'Synonym', NULL, NULL, 10, NULL), ('schema.aggregate', 'schema', 'aggregate', NULL, 9, NULL), ('contract', 'Contract', NULL, NULL, 9, NULL), --service broker ('assembly', 'assembly', NULL, NULL, 9, NULL), --('database','database',NULL,NULL, 8, NULL), ('schema.Default', 'schema', 'Default', NULL, 9, NULL), ('Event Notification', 'Event Notification', NULL, NULL, 9, NULL), ('fileGroup', 'fileGroup', NULL, NULL, 9, NULL), ('fileGroup.Logical file Name', 'fileGroup', 'Logical file Name', NULL, 9, NULL), ('schema.function', 'Schema', 'Function', NULL, 9, NULL), ('schema.function.column', 'Schema', 'Function', 'Column', 9, NULL), ('schema.function.Constraint', 'Schema', 'Function', 'Constraint', 9,NULL), ('schema.function.Parameter', 'Schema', 'Function', 'Parameter', 9, NULL), ('Message type', 'Message type', NULL, NULL, 9, NULL), ('partition Function', 'partition Function', NULL, NULL, 9, NULL), ('partition Scheme', 'partition Scheme', NULL, NULL, 9, NULL), ('schema.Procedure', 'schema', 'Procedure', NULL, 9, NULL), ('schema.Procedure.Parameter', 'schema', 'Procedure', 'Parameter', 9, NULL), ('schema.Queue', 'schema', 'Queue', NULL, 9, NULL), --Service Broker ('schema.Queue.Event Notification', 'schema', 'Queue', 'Event Notification', 9, NULL ), --Service Broker ('Remote Service Binding', 'Remote Service Binding', NULL, NULL, 9, NULL), --Service Broker ('route', 'route', NULL, NULL, 9, NULL), --Service Broker ('schema.Rule', 'schema.Rule', NULL, NULL, 9, NULL), ('Schema', 'Schema', NULL, NULL, 9, NULL), ('Service', 'Service', NULL, NULL, 9, NULL), ('Schema.Service', 'Schema', 'Service', NULL, 9, NULL), ('Schema.Synonym', 'Schema', 'Synonym', NULL, 9, NULL), ('Schema.Table', 'Schema', 'Table', NULL, 9, NULL), ('Schema.Table.Column', 'Schema', 'Table', 'Column', 9, NULL), ('Schema.Table.Constraint', 'Schema', 'Table', 'Constraint', 9, NULL), ('Schema.Table.Index', 'Schema', 'Table', 'Index', 9, NULL), ('Schema.Table.Trigger', 'Schema', 'Table', 'Trigger', 9, NULL), ('Symmetric Key', 'Symmetric Key', NULL, NULL, 9, NULL), ('trigger', 'trigger', NULL, NULL, 9, NULL), --DDL Triggers only (alters any trigger on the database) ('type', 'type', NULL, NULL, 9, NULL), --backward compatibility only ('Schema.Type', 'Schema', 'Type', NULL, 9, NULL), ('Schema.View', 'Schema', 'View', NULL, 9, NULL), ('Schema.View.column', 'Schema', 'View', 'column', 9, NULL), ('Schema.View.index', 'Schema', 'View', 'index', 9, NULL), ('Schema.View.Trigger', 'Schema', 'View', 'Trigger', 9, NULL), ('Schema.XML Schema Collection', 'Schema', 'XML Schema Collection', NULL, 9, NULL ) ) TheHierarchies(Hierarchy, Level0, Level1, Level2, LowestVersion, HighestVersion ); --find what version of SQL Server you are using SELECT @SQLVersion = @@microsoftversion / POWER(2, 24); --abandon the procedure if this version is not supported IF @SQLVersion NOT BETWEEN 8 AND 14 BEGIN RAISERROR('sorry but sp_DbDoc is not written for SQL Server %s',16, 1, @SQLVersion ); RETURN 1; END; --if we just want to list out what is possible by way of extended properties IF @Function = 'possible' BEGIN SELECT [@hierarchies].Hierarchy FROM @hierarchies WHERE @SQLVersion BETWEEN [@hierarchies].LowestVersion AND COALESCE([@hierarchies].HighestVersion, 14) ORDER BY [@hierarchies].Level1, [@hierarchies].Level0; RETURN 0; END; --find out the appropriate values for the levels when calling the built-in EPs SELECT @Level0 = [@hierarchies].Level0, @Level1 = [@hierarchies].Level1, @Level2 = [@hierarchies].Level2, @LowestVersion = [@hierarchies].LowestVersion, @HighestVersion = COALESCE([@hierarchies].HighestVersion, 14) FROM @hierarchies WHERE [@hierarchies].Hierarchy LIKE @hierarchy; SELECT @Hits = @@RowCount; --was it ambiguous? IF @Hits <> 1 BEGIN SELECT @ErrorMessage = CASE WHEN @Hits > 1 THEN 'Ambiguous' ELSE 'Unknown' END; RAISERROR('%s hierarchy ''%s''', 16, 1, @ErrorMessage, @hierarchy); RETURN 1; END; --is what you've chosen appropriate for our version? IF(@SQLVersion NOT BETWEEN @LowestVersion AND @HighestVersion) BEGIN RAISERROR('sorry but %s hierarchy not in SQL Server %d', 16, 1, @hierarchy, @SQLVersion ); RETURN 1; END; --work out the name of the property SELECT @Split = CHARINDEX('.', @object + '.', 1); SELECT @Split2 = CHARINDEX('.', @object + '....', @Split + 1); SELECT @Split3 = CHARINDEX('.', @object + '....', @Split2 + 1); SELECT @Property = CASE WHEN LEN(@object) > 0 THEN LEFT(@object, @Split - 1)ELSE NULL END; IF @Level0 IS NOT NULL SELECT @Name0 = @Property, @Property = NULL; SELECT @Property = CASE WHEN @Split BETWEEN 1 AND LEN(@object) THEN SUBSTRING( @object,@Split + 1, @Split2 - @Split - 1) ELSE @Property END; IF @Level1 IS NOT NULL SELECT @Name1 = @Property, @Property = NULL; SELECT @Property = CASE WHEN @Split2 BETWEEN @Split AND LEN(@object) THEN SUBSTRING( @object,@Split2 + 1, @Split3 - @Split2- 1) ELSE @Property END; IF @Level2 IS NOT NULL SELECT @Name2 = @Property, @Property = NULL; SELECT @Property = CASE WHEN @Split3 BETWEEN @Split2 AND LEN(@object) THEN SUBSTRING( @object,@Split3 + 1,2000) ELSE @Property END; DECLARE @ObjectPath VARCHAR(100) SELECT @Objectpath=COALESCE(@name0+'.','')+COALESCE(@name1+'.','')+COALESCE(@name2,'') IF COALESCE(@Objectpath,'') <> '' BEGIN IF NOT EXISTS (SELECT * FROM sys.objects WHERE objects.object_id = OBJECT_ID(@Objectpath)) BEGIN RAISERROR('sorry but ''%s'' doesn''t seem to be there in %s', 16, 1, @Objectpath,@Database); RETURN 1; END; END; DECLARE @existing TABLE(value SQL_VARIANT); SELECT @PropertyForAmendment = COALESCE(@Property, 'MS_Description'); --remember what is already there INSERT INTO @existing(value) SELECT value FROM::fn_listextendedproperty (@PropertyForAmendment, @Level0, @Name0, @Level1, @Name1, @Level2, @Name2); IF @value IS NOT NULL OR @Function = 'delete' IF EXISTS (SELECT 1 FROM @existing) BEGIN --it is likely to be an update IF(SELECT COUNT(*) FROM @existing) > 1 BEGIN RAISERROR('Ambiguous property spec', 16, 1); RETURN 1; END; IF @Function = 'delete' BEGIN EXECUTE @Return = sys.sp_dropextendedproperty @PropertyForAmendment, @Level0, @Name0, @Level1, @Name1, @Level2, @Name2; END; ELSE BEGIN IF @Function = 'append' SELECT @value = (SELECT CAST([@existing].value AS VARCHAR(8000))FROM @existing) + ', ' + CAST(@value AS VARCHAR(8000)); EXECUTE @Return = sys.sp_updateextendedproperty @PropertyForAmendment, @value, @Level0, @Name0, @Level1, @Name1, @Level2, @Name2; END; END; ELSE --whether append or add BEGIN EXECUTE @Return = sys.sp_addextendedproperty @PropertyForAmendment, @value, @Level0, @Name0, @Level1, @Name1, @Level2, @Name2; END; IF @Return <> 0 BEGIN RAISERROR('sorry but there was an error with %s', 16, 1, @object); RETURN 1; END; --whatever else you do, show what is now there SELECT COALESCE(objname, 'Database') AS object, name, value FROM::fn_listextendedproperty(@Property, @Level0, @Name0, @Level1, @Name1, @Level2, @Name2); --Select @Property,@Level0, @name0, @Level1, @name1, @level2, @name2 GO IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE objects.name = 'sp_DbDoc' AND objects.is_ms_shipped = 1 ) EXEC sys.sp_MS_marksystemobject 'sp_DbDoc'; |
Of course, ultimately, extended properties are just one of the various means of ensuring that your databases are well-documented and easily understood, such as using long descriptive object names.
Load comments