我的公司与许多客户的数据打交道,但我们忽略了记录数据库中表格和字段的含义。为了解决这个问题,我编写了一些存储过程,但似乎只适用于它们所在的数据库。我希望在服务器上有一个存储过程的实例,可以用于所有数据库,但是我不知道如何实现这一点。以下是存储过程:
存储过程1 - sp_GetTableDocumentation
Create Procedure sp_GetTableDocumentation(@TableName SYSNAME)
AS
SELECT
@TableName AS [Table Name]
,'' AS [Column Name]
,CONVERT(NVARCHAR(MAX), ISNULL(D.value, '')) AS [Description]
FROM sys.Tables AS T
OUTER APPLY (SELECT TOP 1 * FROM ::fn_listextendedproperty('Description', 'SCHEMA', 'dbo', 'TABLE', @TableName, NULL, NULL)) AS D
WHERE T.Name = @TableName
UNION ALL
SELECT
@TableName AS [Table Name]
,C.Name AS [Column Name]
,CONVERT(NVARCHAR(MAX), ISNULL(D.value, '')) AS [Description]
FROM sys.Tables AS T
INNER JOIN sys.Columns AS C ON T.Object_id = C.Object_id
OUTER APPLY (SELECT TOP 1 * FROM ::fn_listextendedproperty('Description', 'SCHEMA', 'dbo', 'TABLE', @TableName, 'COLUMN', C.Name)) AS D
WHERE T.Name = @TableName
GO
Procedure 2 - sp_SetTableDocumentation
Create Procedure sp_SetTableDescription(
@schemaName sysname
, @tableName sysname
, @description sql_variant
)
As
If Exists (
Select 1
From fn_listextendedproperty('Description','SCHEMA',@schemaName,'TABLE',@tableName,NULL,NULL)
)
exec sp_DropExtendedProperty 'Description','SCHEMA',@schemaName,'TABLE',@tableName
If (Not @description Is Null) And (Not @description = '')
exec sp_AddExtendedProperty 'Description', @description,'SCHEMA',@schemaName,'TABLE',@tableName
GO
Procedure 3 - sp_SetTableDescription
Create Procedure sp_SetTableDescription(
@schemaName sysname
, @tableName sysname
, @description sql_variant
)
As
If Exists (
Select 1
From fn_listextendedproperty('Description','SCHEMA',@schemaName,'TABLE',@tableName,NULL,NULL)
)
exec sp_DropExtendedProperty 'Description','SCHEMA',@schemaName,'TABLE',@tableName
If (Not @description Is Null) And (Not @description = '')
exec sp_AddExtendedProperty 'Description', @description,'SCHEMA',@schemaName,'TABLE',@tableName
GO
Procedure 4 - sp_SetColumnDescription
CREATE PROCEDURE sp_SetColumnDescription (
@schemaName SYSNAME
,@tableName SYSNAME
,@columnName SYSNAME
,@description SQL_VARIANT
)
AS
IF EXISTS (
SELECT 1
FROM fn_listextendedproperty('Description', 'SCHEMA', @schemaName, 'TABLE', @tableName, 'COLUMN', @columnName)
)
EXEC sp_DropExtendedProperty 'Description','SCHEMA',@schemaName,'TABLE',@tableName,'COLUMN',@columnName
IF (NOT @description IS NULL) AND (NOT @description = '')
EXEC sp_AddExtendedProperty 'Description',@description,'SCHEMA',@schemaName,'TABLE',@tableName,'COLUMN',@columnName
GO
谢谢
sp_
命名约定对于用户定义的数据库对象来说是不好的实践。 - Lukasz Szozda