Skip to content

Instantly share code, notes, and snippets.

@ncalm
Last active December 19, 2023 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncalm/cb43649bebec83f3adaa017652c2a180 to your computer and use it in GitHub Desktop.
Save ncalm/cb43649bebec83f3adaa017652c2a180 to your computer and use it in GitHub Desktop.
This SQL Server procedure encapsulates the process of adding or changing the Description extended property on a table
DROP PROCEDURE IF EXISTS change_table_description;
GO
CREATE PROCEDURE change_table_description (
@table_schema nvarchar(128),
@table_name nvarchar(128),
@description nvarchar(255)
)
AS
BEGIN
-- Validate parameters
IF NOT EXISTS (SELECT * FROM information_schema.tables
WHERE table_schema = @table_schema AND table_name = @table_name)
BEGIN
RAISERROR('The specified table or schema does not exist.', 16, 1);
RETURN;
END
BEGIN TRY
BEGIN TRANSACTION;
DECLARE @full_name nvarchar(261) = QUOTENAME(@table_schema) + '.' + QUOTENAME(@table_name);
IF EXISTS (
SELECT *
FROM sys.extended_properties
WHERE major_id = OBJECT_ID(@full_name)
AND minor_id = 0
AND name = N'Description'
)
BEGIN
EXEC sp_dropextendedproperty
@name = N'Description',
@level0type = 'Schema',
@level0name = @table_schema,
@level1type = 'Table',
@level1name = @table_name;
END
-- Add a table description in SQL Server
EXEC sp_addextendedproperty
@name = 'Description',
@value = @description,
@level0type = 'Schema',
@level0name = @table_schema,
@level1type = 'Table',
@level1name = @table_name;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
THROW; -- Re-throw the caught exception
END CATCH
END
DECLARE @schema nvarchar(128) = 'dbo';
DECLARE @table nvarchar(128) = 'tripdata';
DECLARE @full nvarchar(261) = @schema + '.' + @table;
EXEC change_table_description @schema, @table, 'new table description';
SELECT *
FROM sys.extended_properties
WHERE major_id = OBJECT_ID(@full)
AND minor_id = 0
AND name = N'Description';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment