Querying a really badly designed table

I am working on an application with a number of tables (which I can't change) that have data of the form a1, b1, c1... a2, b2, c2...a3, b3, c3... The tables contain 5 to 10 sets of data in each row.
I want to create a stored procedure to return a cursor with a row for each set of data for a row of the table. I know I can use unions:
select a1 as a, b1 as b , c1 as c... from sometable where pk=@pk
union
select a2, b2, c2... from sometable where pk=@pk
union
select a3...
Is there a way that is more efficient (eliminates requerying the table and all the unions)?
[609 byte] By [GregLee] at [2007-12-19]
# 1
While the structure remains the same, the answer is no. However, you may create another table which structure will suits your needs and which data maintened by the triggers on the source table (thoug this may impact the data modification).
gavrilenko_s at 2007-9-9 > top of Msdn Tech,SQL Server,Transact-SQL...
# 2

Been there done that :) If the data isn's so terribly large, consider building a view:

create view someLessDenormalizedTable
as
select sometable.key, 1 as order, a1 as a, b1 as b , c1 as c... from sometable
union ALL --make sure to use ALL to avoid the sort
select sometable.key, 2 as order, a2, b2, c2... from sometable
union
select a3...

Can't guarantee performance (of course) but it would certainly be worth a try. You could get rid of null rows also.

# 3

I am guessing you are probably not using SQL 2005, but if your are, there is an UNPIVOT operator:

http://msdn2.microsoft.com/en-us/library/ms177410.aspx

Shughes at 2007-9-9 > top of Msdn Tech,SQL Server,Transact-SQL...

SQL Server

Site Classified