我的公司使用来自许多客户的数据,而忽略了记录数据库的表和字段所代表的内容。为了解决这个问题,我编写了一些存储过程,这些存储过程似乎只对它们所依赖的数据库有效。我想在服务器上有一个存储过程的实例,该实例可以在其所有数据库上使用,但不知道如何实现。步骤如下:
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
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
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_”开头,位于主数据库中,并标记为sys.sp_MS_MarkSystemObject,则可以像这样调用它:
Exec somedb.dbo.sp_GetTableDocumentation Exec anotherdb.dbo.sp_GetTableDocumentation
如果您可以接受将存储过程放入主数据库,那么这很好。