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
 need help for a query that contains variables

Author  Topic 

ann06
Posting Yak Master

171 Posts

Posted - 2010-06-08 : 02:38:50
hi,
i have this simple query where i declared the columns and table names as variables like this


Declare @viewColumns NVARCHAR(254)
set @viewColumns='docno,indocno,subject'

Declare @viewTables NVARCHAR(500)
set @viewTables = 'technical_main'

select @viewColumns
from @viewTables

its showing error 'Must declare the variable '@viewTables''.
can't i do such ??
thanks and regards

sakets_2000
Master Smack Fu Yak Hacker

1472 Posts

Posted - 2010-06-08 : 02:44:16
Google for dynamic sql if your variables @viewColumns and @viewTables would change with time.
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2010-06-08 : 02:50:03
what you want cannot be done without Dynamic SQL

read this The Curse and Blessings of Dynamic SQL


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-06-08 : 03:04:07
Also beware of SQL Injection and here is a derived table approach that can avoid it
http://beyondrelational.com/blogs/madhivanan/archive/2010/05/14/derived-table-new-approach-to-avoid-sql-injection.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -