943,891 Members | Top Members by Rank

Ad:
  • MS SQL Discussion Thread
  • Unsolved
  • Views: 5338
  • MS SQL RSS
Jun 7th, 2008
0

dynamic sql query...

Expand Post »
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
MS SQL Syntax (Toggle Plain Text)
  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 ??
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
sangfroid is offline Offline
2 posts
since Oct 2006
Jun 9th, 2008
0

Re: dynamic sql query...

MS SQL Syntax (Toggle Plain Text)
  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
Reputation Points: 10
Solved Threads: 13
Light Poster
huangzhi is offline Offline
48 posts
since Feb 2008
Jan 13th, 2011
0

Dynamic Sp

MS SQL Syntax (Toggle Plain Text)
  1. declare @query nvarchar(Max) ,@tbl nvarchar(Max) ,@col nvarchar(Max) ,@val nvarchar(Max)
  2. -- give tbl=tablename,col=column,val=value
  3. SET @query='select @retVal= count(*) from '+@tbl+' where '+@col+' like ''%'+@val+'%'''
  4.  
  5. EXECUTE sp_executesql @query, N'@retVal int OUTPUT', @retVal OUTPUT
  6.  
  7. SELECT @retVal
Reputation Points: 10
Solved Threads: 0
Newbie Poster
harie.in is offline Offline
1 posts
since Jan 2011

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in MS SQL Forum Timeline: Save table data to another table
Next Thread in MS SQL Forum Timeline: Constraint where both columns cannot be null, but one can





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC