我只有几个表,其中一个是Employee表,其列为eid,ename,sal,deptno。当我写查询
select * from employee
输出为:
eid ename sal deptno
1 Amit 10000 10
2 Alice 20000 20
3 Bob 12000 15
但是我想要一些企业名称(例如,雇员标识符,雇员名称,雇员工资,雇员部门编号),而不是不使用别名的物理列名称。我已经将业务列名称存储在诸如metadata_rename表之类的表中。
Metadata_rename table.
----------------------------------------------------------------
DBname tablename ColumnName BusinessColumnName
----------------------------------------------------------------
dbo emp ID Identifier
dbo emp FirstName First Name
dbo emp LastName Last Name
dbo employee eid Employee Identifier
dbo employee ename Employee Name
dbo employee sal Employee Salary
dbo employee deptno Employee Depatment Number
实时表更多,列也为100-150,因此别名不是一个好的选择。我们可以动态地做到吗?
相反,我们可以传递参数和所有参数。
预期输出: 从员工那里选择开斋节;
提交 爱丽丝 鲍勃
Select * from employee;
------------------------------------------------------------------------------
Employee Identifier Employee Name Employee Salary Employee Dept. Number
------------------------------------------------------------------------------
1 Amit 10000 10
2 Alice 20000 20
3 Bob 12000 15
答案 0 :(得分:0)
我通常认为这是一个可怕的想法,但是这个想法吸引了我。这绝对有效-我尝试了。您需要将其扩展到另一层以添加数据库名称。
DECLARE @tableName AS VARCHAR(64) = 'employee'
DECLARE @query AS VARCHAR(1024) = (
'SELECT ' + STUFF((
SELECT ',' + s.COLUMN_NAME + ' AS [' + ISNULL(a.BusinessColumnName, s.COLUMN_NAME) + ']'
FROM INFORMATION_SCHEMA.COLUMNS AS s
LEFT JOIN Metadata_rename AS a ON a.ColumnName = s.COLUMN_NAME
WHERE s.TABLE_NAME = @tableName
FOR XML PATH ('')), 1, 1, '')
) + ' FROM ' + @tableName
EXEC (@query)