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 2005 Forums
 Transact-SQL (2005)
 problem dynamically selecting database

Author  Topic 

mayerl
Yak Posting Veteran

95 Posts

Posted - 2010-04-06 : 09:00:53
Morning.

I am trying to write a query that dynamically generates the database name. the idea is the finance people want to query the "frozen" databases to get labor numbers. This is what i have so far, every time I try to run it it doesn't like my join and I get the message:

Msg 102, Level 15, State 1, Line 22
Incorrect syntax near 'L2'.


Declare @CreateLastDBName varchar(100);
Declare @CreateLast2DBName varchar(100);
Declare @LastMthDate varchar(100);
Declare @Last2MthDate varchar(100);
Declare @Sql varchar(MAX);

SELECT @LastMthDate= CAST(YEAR(GETDATE()) AS VARCHAR(4)) + left(CONVERT(char(20),DATEADD(MONTH,-1,GETDATE()),101),2)

SELECT @Last2MthDate= CAST(YEAR(GETDATE()) AS VARCHAR(4)) + left(CONVERT(char(20),DATEADD(MONTH,-2,GETDATE()),101),2)

SET @CreateLastDBName ='P'+@LastMthDate

SET @CreateLast2DBName='P'+@Last2MthDate

select (L2.totalHours-L1.totalHours)totalHours,
(L2.labor - L1.labor)labor,
(L2.oh - L1.oh) oh,
(L2.newlabor- L1.newlabor) newlabor,
(L2.newoh- L1.newoh) newoh,
L2.department
from @CreateLast2DBName.vw_Apply_Labor_Last2Mnths L2
inner join @CreateLastDBName.vw_Apply_Labor_LastMnth L1
on L2.department = L1.Department


Any thoughts would be appreciated.

Thanks

Laura

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-04-06 : 09:06:48
Make sure you read this fully
www.sommarskog.se/dynamic_sql.html

Madhivanan

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

mayerl
Yak Posting Veteran

95 Posts

Posted - 2010-04-06 : 09:10:19
Dang....Thanks Madhivanan. Back to the drawing board.
Go to Top of Page
   

- Advertisement -