假设我们有一张桌子:
CREATE TABLE new_table
(
regionname character varying(10),
year integer,
month integer,
value integer
)
如何选择例如第3列"月"不使用
SELECT month FROM new_table
但是类似
SELECT "the 3rd column" FROM new_table
答案 0 :(得分:0)
我想先说一个表架构可能会发生变化,因此列顺序可能会发生变化,从而破坏数据库外的所有现有查询,存储过程或代码。你到底想要完成什么?你只想用数字而不是名字吗?
这个答案:
Declare @WhichOne int;
Declare @Sql varchar(200);
Set @WhichOne = 2;
With cte As
(Select name, Row_Number() Over (Order By column_id) As rn
From sys.columns
Where Object_Name(object_id) = 'MyTable')
Select @Sql = 'Select ' + QuoteName(name) + ' From MyTable'
From cte
Where rn = @WhichOne;
Exec(@Sql);
可在此处找到:http://www.codeproject.com/Questions/148495/Solved-SELECT-columns-by-column-index-NOT-by-colu