如何在SQL SERVER 2008中获取表名,列名,列描述,列值

时间:2012-10-09 12:15:13

标签: sql-server sql-server-2008

我有一个名为Users的表:

UserID  UserName  UserPwd
  1      zhang     123456
  2      li        455667
  3      wang      332222

我想得到如下结果(UserID ='1'):

tableName   columnName   columnDescribe      columnValue
  Users       UserName     The user name         zhang
  Users       UserPwd      The user password     123456

任何人都可以帮助我吗?

SELECT t.name AS [tableName],
   c.name AS [columnName],
   cd.value AS [columnDescribe]
FROM  sysobjects t
INNER JOIN sysusers u
 ON  u.uid = t.uid
LEFT OUTER JOIN sys.extended_properties td
 ON  td.major_id = t.id
    AND  td.minor_id = 0
 AND  td.name = 'MS_Description'
INNER JOIN syscolumns c
 ON  c.id = t.id
LEFT OUTER JOIN sys.extended_properties cd
 ON  cd.major_id = c.id
 AND  cd.minor_id = c.colid
 AND  cd.name = 'MS_Description'
WHERE t.type = 'u' AND t.name='Users'
ORDER BY t.name, c.colorder

2 个答案:

答案 0 :(得分:2)

试试这个:

select  'Users' as tableName,
        'UserName' as columnName ,
        'The user name' as columnDescribe,
        UserName as columnValue 
from Users where [UserID]=1 
union all
select  'Users' as tableName,
        'UserPwd' as columnName ,
        'The user name' as columnDescribe,
        UserPwd as columnValue 
from Users where [UserID]=1 


SQL fiddle demo

答案 1 :(得分:0)

试试这个:

select OBJECT_NAME(object_id) as tablename,
       s.name as columnname,
       ex.value as 'columnDescribe',
       CASE WHEN s.name='Username' then UserName else UserPwd end from sys.columns s inner join users_1
on object_id=OBJECT_id('users_1') and s.name in('UserName','UserPwd')
inner join sys.extended_properties ex
on object_id=OBJECT_id('users_1') and s.name = ex.name
where UserID=1