Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help Writing query

Author  Topic 

zwheeler
Starting Member

25 Posts

Posted - 2012-02-07 : 17:06:08
hi
I have a query and it works when i hard code the column name in the select statement of the openquery.
Select
cast([pk_id] as int) fk_id,
[1978q1] intRate
from OpenQuery(Moodys_Linked,'Select * from [Sheet1$]')

output example

fk_id intRate
1 1.25
2 0.9
3 0.606

however, i have to get the intRate for each quarter for 57 years and i am trying to build the column name for the intRate ([Year + Quarter])
so I would have [1964Q1], [1964Q2],[1964Q3],[1964Q4],[1965Q1],.......... (NOTE: In the spreadsheet these represent the column names.

I have tried to to build a while loop to create these column names dynamically

[code="sql"]

declare @counter int
declare @count1 int

set @counter = 1964
set @count1 = 1
/** Insert data from moodys extract **/
while @count1 < 5
begin
while @counter < 2022
begin

Select
cast([pk_id] as int) fk_id,
cast ('[' + cast(@counter as varchar) + 'Q' + cast(@count1 as varchar) + ']' as varchar ) intRate
from OpenQuery(Moodys_Linked,'Select * from [Sheet1$]')

set @counter = @counter + 1
end
set @count1 = @count1 + 1
set @counter = 1964
end

[/code/

however, instead of creating the name in the spreadsheet and returning the values it is simply creating a varchar value for each record
i.e.
fk_id intRate
1 1978Q1
2 1978Q2
3 1978Q3
4 1978Q4
5 1979Q1
...............

Is it possible to create column name of a table or excel spreadsheet from scratch (i.e. dynamically)

or

what am i doing wrong

any help is greatly appreciated.

Thanks in advance

X002548
Not Just a Number

15586 Posts

Posted - 2012-02-07 : 17:19:46
How many columns does sheet 1 HAVE?

You might need dynamic sql

What is the result set suppose to look like?

You must need a column that defines WHERE the data came from



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page
   

- Advertisement -