我的公司使用來自衆多客戶的數據,並忽略記錄我們的數據庫表和字段所代表的內容。爲了解決這個問題,我編寫了一些存儲過程,這些存儲過程似乎只適用於他們所在的數據庫。我想在服務器上有一個存儲過程的實例,可以在其所有數據庫上使用,但無法弄清楚如何實現這一點。下面是程序:SQL存儲過程 - 從多個數據庫執行
步驟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
步驟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
程序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
步驟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
感謝
對於用戶定義的db對象,'sp_'命名約定是不好的做法 – lad2025
這裏是一篇文章,介紹爲什麼sp_是不好的做法。 http://sqlperformance.com/2012/10/t-sql-queries/sp_prefix –
你將不得不實現動態sql來使其成爲一組通用的過程,以便您可以定義它將針對哪個數據庫執行。它可以完成,但會是一個相當大的工作,因爲除了實際使它與動態SQL功能,它也需要從SQL注入安全。 –