Friday, February 17, 2012

Dynamic sql statement

I would like to know if it is possible to pass a table name to the from section of a sql select statement?
Something like:
Declare @.paramTable as nvarchar(10)
Set @.paramTable = TableName
Select firstname, surname from @.paramTable
Is this possible?Only using dynamic SQL, where you SELECT statement is constructed as a string and then executed.
This is not advisable...|||or sp_execute_sql|||Ok. What about in a stored procedure then.

Say I have multiple tables each one contacining data from each month of the year. If I pass through January it must use the January table, February the February table and so on.
Any idea how this can be done?|||create a partitioned view then...are you creating tables on the fly?|||A table named "January"? I am afraid to ask what you do at the start of a new year.
You need to rethink your design.|||Please I am not that dumb blindman, give me a little credit. Purely was an example and a very rushed one at that.|||http://sommarskog.se/dynamic_sql.html|||good one, jez

from that article:Now, let's make this very clear: this is a flawed table design. You should not have one sales table per month, you should have one single sales table, and the month that appear in the table name, should be the first column of the primary key in the united sales table. At least logically. Sometimes, when you have huge tables (say over 10 GB in size), partitioning can be a good idea, but you should do it right and use partitioned views, that we will look at in this section. I like to make the point that since SQL Server is a enterprise RDBMS, it can handle very large tables very efficiently, as long as you keep in mind that good indexing is essential. A few million rows is no cause for concern.|||i would edit that quote and replace "partitioned views" with "table using a partition function". less to manage that way. only exists on 2005 though.

No comments:

Post a Comment