SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 Old Forums
 CLOSED - General SQL Server
 Query by Column Name
 Forum Locked
 Printer Friendly
Author Previous Topic Topic Next Topic  

superuser
Starting Member

2 Posts

Posted - 09/06/2006 :  06:51:28  Show Profile
Hi Friends!

I am trying to query a certain column that matches the current month, but it is not working correctly. The columns are named by the month. The below will not pull the data only the column name.




------------does not work----------------
declare @m as varchar(3)
set @m = left(getdate(),3)--    @m = Sep
select @m, dept from t_DLEUBudget
-----------------------------------------
 
-------------works great-----------------
select Sep, dept from t_DLEUBudget
-----------------------------------------

SwePeso
Patron Saint of Lost Yaks

Sweden
30242 Posts

Posted - 09/06/2006 :  06:57:58  Show Profile  Visit SwePeso's Homepage
Your data is not normalized, hence you must use DYNAMIC SQL, which most of the time is bad design.
See http://www.sommarskog.se/dynamic_sql.html

declare @sql varchar(8000), @m char(3)

set @m = datename(month, getdate())

set @sql = 'select ' + @m + ', dept from t_DLEUBudget'

exec (@sql)


Peter Larsson
Helsingborg, Sweden

Edited by - SwePeso on 09/06/2006 07:01:02
Go to Top of Page

chiragkhabaria
Flowing Fount of Yak Knowledge

India
1907 Posts

Posted - 09/06/2006 :  06:58:27  Show Profile  Visit chiragkhabaria's Homepage  Send chiragkhabaria a Yahoo! Message
you need use dyanmic sql for this.

Declare @Qry varchar(1000)
declare @m as varchar(3)
set @m = left(getdate(),3)--    @m = Sep
Set @Qry = 'select ' +  @m + ', dept from t_DLEUBudget'
Exec(@Qry)


Chirag
Go to Top of Page

chiragkhabaria
Flowing Fount of Yak Knowledge

India
1907 Posts

Posted - 09/06/2006 :  07:00:31  Show Profile  Visit chiragkhabaria's Homepage  Send chiragkhabaria a Yahoo! Message


Chirag
Go to Top of Page

superuser
Starting Member

2 Posts

Posted - 09/06/2006 :  07:00:39  Show Profile
Wow! you guys are awesome! Thanks!
Go to Top of Page

madhivanan
Premature Yak Congratulator

India
22755 Posts

Posted - 09/06/2006 :  09:09:13  Show Profile  Send madhivanan a Yahoo! Message
Also read about Normalisation
http://www.datamodel.org/NormalizationRules.html


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
  Previous Topic Topic Next Topic  
 Forum Locked
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.11 seconds. Powered By: Snitz Forums 2000