ram*_*ams 34 sql t-sql sql-server ordinals sql-server-2005
是否可以使用表列的ordinal_position选择列数据?我知道使用序数位置是一种不好的做法,但对于一次性数据导入过程,我需要能够使用序数位置来获取列数据.
所以举个例子
create table Test(
Col1 int,
Col2 nvarchar(10)
)
Run Code Online (Sandbox Code Playgroud)
而不是使用
select Col2 from Test
Run Code Online (Sandbox Code Playgroud)
我能写吗?
select "2" from Test -- for illustration purposes only
Run Code Online (Sandbox Code Playgroud)
Boo*_*Boy 15
你必须做类似的事情
declare @col1 as varchar(128)
declare @col2 as varchar(128)
declare @sq1 as varchar(8000)
select @col1 = column_name from information_schema.columns where table_name = 'tablename'
and ordinal_position = @position
select @col2 = column_name from information_schema.columns where table_name = 'tablename'
and ordinal_position = @position2
set @sql = 'select ' + col1 ',' + col2 'from tablename'
exec(@sql)
Run Code Online (Sandbox Code Playgroud)
小智 13
如果你知道列的数量,但不知道它的名称和类型,你可以使用以下技巧:
select NULL as C1, NULL as C2 where 1 = 0
-- Returns empty table with predefined column names
union all
select * from Test
-- There should be exactly 2 columns, but names and data type doesn't matter
Run Code Online (Sandbox Code Playgroud)
因此,您将拥有一个包含2列[C1]和[C2]的表.如果表中有100列,则此方法不是很有用,但它适用于预定义列数较少的表.
您可以使用此查询
select * from information_schema.columns
Run Code Online (Sandbox Code Playgroud)
获取列的序数位置.就像迈克尔哈伦写的那样,你必须使用它来构建一个动态查询,无论是在代码中还是在传递列位置的sproc中.
FWIW,这是纯粹的邪恶.
此外,deathofrats是正确的,你不能真的这样做,因为你将建立一个基于位置的列名称的常规查询.
是的,您可以通过对系统表进行一些非常丑陋的点击来做到这一点。您可能需要进入动态 sql 的世界。
我真的非常不推荐这种方法。
如果这没有阻止您,那么这可能会让您开始(参考):
select table_name, column_name, ordinal_position, data_type
from information_schema.columns
order by 1,3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90925 次 |
| 最近记录: |