Wednesday 18 May 2011

Retrieve a SQL Column based on its Ordinal Value

We have a columns ordinal position and want to retrieve the data based on this value. Not something we really want to do - but out of interest, how can it be done?

Solution:
/* find a column based on its ordinal value) -- handy keep me*/declare @col1 as varchar(128)
select @col1 = column_name from information_schema.columns where table_name = 'Trade'and ordinal_position = 2 --@position
select @col1

Note, to retrieve the column ordinal in the first place select column_id (ie the ordinal value) from sys.columns.. like this:
SELECT c.[name] , column_id
FROM sys.columns c
LEFT JOIN [develop].[internal_fields] fi ON fi.[field_name] = c.[name]
LEFT JOIN [meta].[audit_internal_udfs] iu ON iu.[column_name] = c.[name]
WHERE c.[object_id] = OBJECT_ID( 'dbo.Trade') AND c.[name] != 'TradeId' AND c.[name] NOT IN ( 'CreateDate', 'ChangeDate', 'RowVersion', 'ProcessingDateTime') AND c.system_type_id != 241 AND fi.[_identity] IS NULL AND iu.[_identity] IS NULL
 

No comments:

Post a Comment