[研究]T-SQL 把欄位名稱包含 CreateDate 的 欄位描述內容 都設定為 "建立日期"
2024-01-25
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19
********************************************************************************
T-SQL 如何把 MyDB資料庫中,資料表名稱 MyTable 開頭的,欄位名稱包含 CreateDate 的 欄位描述內容 ( sys.extended_properties.value ) 都設定為 "建立日期" (不存在,才會增加描述內容;已經有描述內容的,不會修改)
USE MyDB; -- 切換到您的資料庫名稱 DECLARE @ColumnName NVARCHAR(255); DECLARE @TableName NVARCHAR(255); DECLARE ColumnCursor CURSOR FOR SELECT c.name AS ColumnName, t.name AS TableName FROM sys.columns c INNER JOIN sys.tables t ON c.object_id = t.object_id WHERE t.name LIKE '%MyTable%' AND c.name LIKE '%CreateDate%' AND t.is_ms_shipped = 0; OPEN ColumnCursor; FETCH NEXT FROM ColumnCursor INTO @ColumnName, @TableName; WHILE @@FETCH_STATUS = 0 BEGIN IF NOT EXISTS ( SELECT 1 FROM sys.extended_properties WHERE major_id = OBJECT_ID(@TableName) AND minor_id = COLUMNPROPERTY(OBJECT_ID(@TableName), @ColumnName, 'ColumnId') AND name = N'MS_Description' ) BEGIN EXEC sys.sp_addextendedproperty @name = N'MS_Description', @value = N'建立日期', @level0type = N'SCHEMA', @level0name = 'dbo', @level1type = N'TABLE', @level1name = @TableName, @level2type = N'COLUMN', @level2name = @ColumnName; END; FETCH NEXT FROM ColumnCursor INTO @ColumnName, @TableName; END; CLOSE ColumnCursor; DEALLOCATE ColumnCursor; |
********************************************************************************
驗證
USE MyDB; -- 切換到您的資料庫名稱 SELECT t.name AS TableName, c.name AS ColumnName, ep.value AS ColumnDescription FROM sys.tables t JOIN sys.columns c ON t.object_id = c.object_id LEFT JOIN sys.extended_properties ep ON ep.major_id = t.object_id AND ep.minor_id = c.column_id AND ep.class_desc = 'OBJECT_OR_COLUMN' WHERE t.name LIKE '%MyTable%' -- c.name LIKE '%MyColumn%' ORDER BY t.name, c.column_id; |
********************************************************************************
(完)
相關
沒有留言:
張貼留言