日期:2014-05-18  浏览次数:20788 次

关于记录集列标题的应用
我有一个表Admin,列为 ID,name,password
用 select * from Admin 得到
------------------
1 admin admin
2 ma sa
------------------
现在我想得到下面的记录集,怎么实现
-------------------
ID name password ----(注:必须放在第一行)
1 admin admin
2 ma sa
-------------------
我想用SQL语句执行得到,而不是得到第一种记录集,再在程序中取得列标题
谢谢大家!

------解决方案--------------------
declare @sql varchar(8000)
declare @sql1 varchar(8000)
set @sql='select '
set @sql1='select '
select @sql=@sql+''''+name+''''+',' from syscolumns where id=object_id('ADMIN')
set @sql =left(@sql ,len(@sql)-1) + ' union all '
select @sql1=@sql1+'cast( '+name+' as varchar) ,' from syscolumns where id=object_id('ADMIN')
print @sql1
set @sql =@sql+left(@sql1 ,len(@sql1)-1)+ ' from mesel00h ' 
EXEC(@sql)

------解决方案--------------------
SQL code


declare @col varchar(100)
set @col=''
select @col=@col+''''+name+''''+name+',' from syscolumns where id=object_id('admin')
set @col=left(@col,len(@col)-1)
exec('select '+@col+' union all select ltrim(id),name,password from admin')