我在 ExtendedProperties
下面有一张表 --------------------------------------------------------------------------
| DatabaseName | SchemaName | TableName | ColumnName | Description |
---------------------------------------------------------------------------
| database1 | dbo | Users | UserId | this is user id |
---------------------------------------------------------------------------
| database1 | dbo | Users | name | this is user name |
---------------------------------------------------------------------------
| database2 | dbo | Comments | CommentId | this is id |
---------------------------------------------------------------------------
| database2 | dbo | Comments | Description| this is description |
---------------------------------------------------------------------------
该表包含200多个条目。
而不是在SQL Server Management Studio中输入每一列并输入这些描述我想编写一个循环来自动创建每个列的扩展属性。
对于第一行,sql查询如下所示:
USE database1
GO
EXEC sys.sp_addextendedproperty @name=N'Caption',
@value=N'this is user id' , @level0type=N'SCHEMA',
@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Users',
@level2type=N'COLUMN',@level2name=N'UserId'
我想创建一个循环来运行此查询(在C#中,这将类似于下面的内容)
foreach(var row in ExtendedProperties){
USE row.DatabaseName
GO
EXEC sys.sp_addextendedproperty @name=N'Caption',
@value=N row.Description , @level0type=N'SCHEMA',
@level0name=N'dbo', @level1type=N'TABLE',@level1name=N row.TableName,
@level2type=N'COLUMN',@level2name=N row.ColumnName
}
如何在SQL中实现此循环?
答案 0 :(得分:2)
要逐行操作数据SQLServer有一个对象CURSOR
,但在这种情况下我会使用动态sql。
DECLARE @dsql nvarchar(max) = ''
SELECT @dsql += 'USE [' + DatabaseName + '] EXEC sys.sp_addextendedproperty @name=N''Caption'',' +
'@value=''' + [Description] + ''', @level0type=N''SCHEMA'',' +
'@level0name=N''dbo'', @level1type=N''TABLE'', @level1name=N''' + TableName + ''',' +
'@level2type=N''COLUMN'',@level2name=N''' + ColumnName + ''''
FROM dbo.ExtendedProperties
--PRINT @dsql
EXEC sp_executesql @dsql