sql 查询 第二列 字段
不是用列名:select bbb from TableName
而是用数字:select 3 from TableName
不用列名,用数字指定,要查询第3列,怎么查询?
表字段结构如下:
ID aaa bbb ccc
[解决办法]
DECLARE @i INT,@sql VARCHAR(max)
SET @i=3
SELECT @sql='select '+name+' from 表名'
FROM syscolumns
WHERE id=OBJECT_ID('表名') AND colorder=@i
EXEC(@sql)
declare @i int
set @i=2
declare @sql varchar(200)
set @sql='select '+ quotename((select name from sys.syscolumns where ID=OBJECT_ID(TableName) and colid =@i),'')+' from TableName '
exec( @sql)
--drop table tb
create table tb(ID int,aaa varchar(10),bbb varchar(10), ccc varchar(10))
insert into tb
select 1,'a1','b1','c1' union all
select 2,'a2','b2','c2' union all
select 3,'a3','b3','c3'
go
DECLARE @i INT
declare @table_name nvarchar(100)
declare @sql nVARCHAR(4000)
SET @i=3
set @table_name= 'tb'
SELECT @sql='select '+c.name+' from ' +@table_name
FROM sys.tables t
inner join sys.columns c
on t.object_id = c.object_id
WHERE t.name =@table_name
AND c.column_id=@i
--select @sql
/*
select bbb from tb
*/
EXEC(@sql)
/*
bbb
b1
b2
b3
*/