Friday, March 23, 2012

is this Possible

I want to pass a table name to a query
Declare @.Tablename '
Set @.TableName = 'MyTable'
Select * from @.TableName
how can i get this to work, if at all possibleResist the urge!
http://www.sommarskog.se/dynamic_sql.html
Keith
"Peter Newman" <PeterNewman@.discussions.microsoft.com> wrote in message
news:C461CC2C-7B1C-4606-A212-992D61F62B0A@.microsoft.com...
> I want to pass a table name to a query
> Declare @.Tablename '
> Set @.TableName = 'MyTable'
> Select * from @.TableName
> how can i get this to work, if at all possible|||You can use either a table variable or dynamic sql to work with dynamic tabl
e
names, a lot of experts will have tons of bad things to say about "dynamicly
"
creating tables but sometime you just can't help which I hope this is the
case otherwise you shouldn't use it :)
There are limitations to table variables which you can search for on the web
.
There are also limitations and nasties when you use dynamic SQL especially
in webased evironments where people can inject code into yours if they know
their way...
You can also have a look at local and global temp tables for the use of
adhoc tables .
Something that I can think of quickly
Table variable VS temp tables (# tables)
Table variables don't have schema, so you can't use indexing so massive
tables will be slow for querying, temp tables got a schema thus not a proble
m.
There are plenty of differences , pro's and cons for both.
What would be helpful to you is if you tell us what you are trying to
accomplish, then maybe we can be even more helpful.
Some code examples of "normal" table query using dynamic sql and table
variable.
HTH
declare @.mytable table (col1 int)
insert into @.mytable select '1'
select * from @.mytable
/**************/
create table mytable(col1 int)
insert into mytable select '1'
declare @.tablename nvarchar(22)
declare @.sql nvarchar(999)
set @.tablename = 'mytable'
set @.sql = 'select * from ' + @.tablename
exec sp_executesql @.sql
"Peter Newman" wrote:

> I want to pass a table name to a query
> Declare @.Tablename '
> Set @.TableName = 'MyTable'
> Select * from @.TableName
> how can i get this to work, if at all possible

No comments:

Post a Comment