Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trouble with select statement using a variable 1

Status
Not open for further replies.

hrhadin

Programmer
Oct 7, 2003
16
0
0
US
I'm trying to open a cursor using an SQL statement based on a DB whose name changes from month to month. I have the following code:

SET @dProcDate = '02-01-2007 00:00:00'
SET @cMonth = 'Test_' + CASE WHEN MONTH(@dProcDate) < 10 THEN '0' + CAST(MONTH(@dProcDate) AS char(1)) ELSE CAST(MONTH(@dProcDate) AS char(2)) END +
CAST(YEAR(@dProcDate) AS char(4)) + '.Dbo.SomeTable'

DECLARE cur3011 CURSOR LOCAL FAST_FORWARD
FOR
SELECT cAgency
FROM [@cMonth]

open cur3011

I'm receiving the error 'Invalid Object @cMonth'

Does anybody know of a way to accomplish this?
 
It's a variable. I left out the Declare statement for simplicity.
 
2 things

1 dynamic SQL is the way for this

2) this
SET @cMonth = 'Test_' + CASE WHEN MONTH(@dProcDate) < 10 THEN '0' + CAST(MONTH(@dProcDate) AS char(1)) ELSE CAST(MONTH(@dProcDate) AS char(2)) END +
CAST(YEAR(@dProcDate) AS char(4)) + '.Dbo.SomeTable'

can be replaced with this
SET @cMonth = 'Test_' + right(replace(convert(varchar(10),@dProcDate,105),'-',''),6)+ '.Dbo.SomeTable'

Denis The SQL Menace
--------------------
SQL Server Code,Tips and Tricks, Performance Tuning
Google Interview Questions





 
In which case you declare becomes

DECLARE cur3011 CURSOR LOCAL FAST_FORWARD
FOR
SELECT @cMonth

but that means you just get one value and I'm not sure why you would be cursoring in that case.


 
Sorry (should read more carefully). I get it - you are trying to select from the table name you have put into variable and SLQDenis is right.
 
Thanks to SQLDenis for your help. Your tips allowed me to complete the stored procedure I was working on.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top