SQL Comments on Create Table on SQL Server 2008

2020-01-27 04:14发布

I need to create some pretty big tables in SQL Server 2008, while I do have SQL Server Management Studio, I would like to comment the tables and the columns when I create the table. How do I do this?

Example of the query I am running:

CREATE TABLE cert_Certifications
(
  certificationID int PRIMARY KEY IDENTITY,
  profileID int,
  cprAdultExp datetime null
)

I've tried COMMENT'Expiration Date for the Adult CPR' and COMMENT='Expiration Date for the Adult CPR' after the data type, and SQL Server is giving me an error.

7条回答
甜甜的少女心
2楼-- · 2020-01-27 05:19

Altough it does not directly answer original question (J Henzel and Randy Minder already did !) I would like to share something else I just wrote that can be very useful for those who have to comment a lot of tables and columns.

The following queries :

-- Generate comments templates for all tables
SELECT 
'EXEC sys.sp_addextendedproperty
    @name=N''TableDescription'',
    @level0type=N''SCHEMA'',    
    @level1type=N''TABLE'',
    @level0name=N''' + TABLE_SCHEMA + ''',
    @level1name=N''' + TABLE_NAME + ''',
    @value=N''TODO'';'
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME NOT like 'sys%'
order by TABLE_SCHEMA, TABLE_NAME


-- Generate comments templates for all columns
SELECT 'EXECUTE sp_addextendedproperty 
    @name = ''ColumnDescription'', 
    @level0type = ''SCHEMA'', 
    @level1type = N''TABLE'', 
    @level2type = N''COLUMN'', 
    @level0name=N''' + TABLE_SCHEMA + ''',
    @level1name=N''' + TABLE_NAME + ''',
    @level2name = N''' + COLUMN_NAME + ''',
    @value = ''TODO'';'
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA not like 'sys%' and TABLE_NAME not like 'sysdiagrams%'
  order by TABLE_SCHEMA, TABLE_NAME, case when ORDINAL_POSITION = 1 then '0' else COLUMN_NAME end

Will produce in SQL Server output a list of calls to sp_addextendedproperty for all the tables and all the columns existing in your database, by querying on system tables to gather them.

Of course, it will not comment it magically for you, but at least you just have to fill the "TODOs" placeholders with the relevant comment for all objects you would like to describe and to execute it.

It avoids you to write manually all the calls and saves a lot of time, and with it you can't forget a table or column so I hope it will be useful for somebody else.

Side remarks : Just beware on the filters in WHEREs on "sys", it's here to exclude system objects but depending of your objects names you may need a bit of fine tuning of you have tables named alike.

Also, there's no comment at all in my DB so my query returns all tables/columns, it does not consider wether there's already a comment or not on it.

查看更多
登录 后发表回答