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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Creating Dynamic FROM

Author  Topic 

newty25
Starting Member

21 Posts

Posted - 2002-09-05 : 17:21:03
Is there a way in a SQL statement to create a dynamic FROM statement within a select statement so that I can SELECT from a table based on a date value.

Our tables are broken up into monthly tables (the architecture was in place before I got here). I want to be able to do something like


SELECT * FROM Customers + (DATEPART(MM, GETDATE()) + DATEPART(YYYY, GETDATE()))


I want to set up something like this as a view in Db

Thanks in advance!
newty

JustinBigelow
SQL Gigolo

1157 Posts

Posted - 2002-09-05 : 17:34:45
Go with dynamic sql...

declare @SQL varchar(1000)

set @SQL = 'SELECT * FROM Customers' + cast((DATEPART(MM, GETDATE()) + DATEPART(YYYY, GETDATE())) as char(6))

exec(@SQL)

... but if you want this to be a view I think you'll have to wrap it in a stored procedure. Sorry can't test it.

hth,
Justin



Have you hugged your SQL Server today?
Go to Top of Page

MichaelP
Jedi Yak

2489 Posts

Posted - 2002-09-05 : 17:34:46
Do a search for "dynamic sql" on the main site or on the boards.

I think a better solution would be something like the on in the following article.

http://www.sqlteam.com/item.asp?ItemID=684

Michael







<Yoda>Use the Search page you must. Find the answer you will.</Yoda>
Go to Top of Page
   

- Advertisement -