dynamic sql query...

Please support our MS SQL advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2006
Posts: 2
Reputation: sangfroid is an unknown quantity at this point 
Solved Threads: 0
sangfroid sangfroid is offline Offline
Newbie Poster

dynamic sql query...

 
0
  #1
Jun 7th, 2008
Hi
I am trying to write a function in which I customize my select statement. But it is not working as i desire...

It is as
  1. declare @column_name nvarchar(10)
  2. SET @column_name = 'original'
  3. SELECT @column_name FROM DATA
Here original is the name of one of the columns. I wanted to make it such that column_name can be assigned any of the column names and the same piece of code works only by changing the value of @column_name...but it is not working....

any ideas ??
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 42
Reputation: huangzhi is an unknown quantity at this point 
Solved Threads: 13
huangzhi huangzhi is offline Offline
Light Poster

Re: dynamic sql query...

 
0
  #2
Jun 9th, 2008
  1. CREATE TABLE #tmp (Code varchar(255), Price money, Date smalldatetime)
  2.  
  3. INSERT #tmp (Code, Price, Date)
  4. SELECT 'ProductA', 12.00, '12/10/2002' union ALL
  5. SELECT 'ProductA', 12.50, '01/15/2005' union ALL
  6. SELECT 'ProductA', 12.01, '01/02/2008' union ALL
  7. SELECT 'ProductB', 15.12, '12/01/2005' union ALL
  8. SELECT 'ProductB', 16.00, '01/09/2008' union ALL
  9. SELECT 'ProductB', 16.24, '01/15/2008'
  10.  
  11. declare @column_name nvarchar(10)
  12. SET @column_name = 'Code'
  13. exec ('select ' + @column_name + ' from #tmp')
  14.  
  15. SET @column_name = 'Price'
  16. exec ('select ' + @column_name + ' from #tmp')
  17.  
  18. DROP TABLE #tmp
Hence Wijaya
www.ex-Soft.tk
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC