选择数据列的描述不为空,然后将列名替换为描述

时间:2017-07-09 15:29:43

标签: c# sql-server tsql

我有一张桌子' PurchaseOrder'。当列的描述不为空时,我想要选择数据。然后用它的描述替换列的名称。

表PurchaseOrder

ID | Product    |  Use    |   Price   |  Comment 
-----------------------------------------------------
1  | Cellphone  |  true   |   100     |   
2  | Car        |  false  |   10      |   
3  | Table      |  true   |   200     |   

专栏

Name      |    Description
---------------------------
ID        |    Index
Produce   |    Name
Use       |    
Price     |    Sale
Comment   |

选择结果将是

Index  |   Name      |    Sale
--------------------------------
1      |   Cellphone |    100        
2      |   Car       |    10         
3      |   Table     |    200    

现在,我只获得描述

的列
if object_id('tempdb..#dt') is not null drop table #dt
select 
    sc.column_id [Position],
    sc.name [Column],
    sc.max_length [Length],
    sep.value [Description]
into #dt
from sys.tables st
inner join sys.columns sc on st.object_id = sc.object_id
left join sys.extended_properties sep on st.object_id = sep.major_id
                                     and sc.column_id = sep.minor_id
                                     and sep.name = 'MS_Description'
where st.name = 'PurchaseOrder' and sep.value is not null 

如何生成最终数据表?

1 个答案:

答案 0 :(得分:0)

DECLARE 
@TABLE_NAME NVARCHAR(50) = 'PurchaseOrderDetail', 
@TABLE_SCHEMA Nvarchar(50) = 'Purchasing',
@COL_LIST NVARCHAR(MAX),
@SQL NVARCHAR(4000), 
@COL NVARCHAR(500) 

DECLARE c_cursor CURSOR FOR        
SELECT sc.name + ' as ' + QUOTENAME(CAST(sep.value AS varchar)) AS Expr1
FROM   sys.tables AS st INNER JOIN
       sys.columns AS sc ON st.object_id = sc.object_id INNER JOIN
       sys.extended_properties AS sep ON st.object_id = sep.major_id AND sc.column_id = sep.minor_id AND sep.name = 'MS_Description'
WHERE st.name = @TABLE_NAME AND sep.value IS NOT NULL

OPEN c_cursor; 
FETCH NEXT 
FROM c_cursor INTO @COL; 
WHILE ( @@FETCH_STATUS = 0 ) 
BEGIN 
SELECT @COL_LIST = COALESCE(@COL_LIST+',' ,'') + @COL
FETCH NEXT FROM c_cursor 
INTO @col; 
END CLOSE c_cursor; 
DEALLOCATE c_cursor; 

SET @SQL = ' SELECT ' + @COL_LIST +' FROM ' + QUOTENAME(@TABLE_SCHEMA)+'.'+QUOTENAME(@TABLE_NAME) 
PRINT @SQL;
EXEC (@sql);