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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable error

Status
Not open for further replies.

fredong

IS-IT--Management
Sep 19, 2001
332
US

Hi,
I have a variable error that stated that I have to declare @table which I already declare when I run my query below. Please advise. Thanks

DECLARE @YR varchar(4)
DECLARE @QTR varchar(3)
DECLARE @Table varchar(30)


SET @YR = Year(getdate())
If Month(getdate()) IN (1,2,3)
SET @QTR = '_Q1'
If Month(getdate()) IN (4,5,6)
SET @QTR = '_Q2'
If Month(getdate()) IN (7,8,9)
SET @QTR = '_Q3'
If Month(getdate()) IN (10,11,12)
SET @QTR = '_Q4'

SET @Table = 'dbo.AUDIT2' + @YR

select * from @Table (nolock)
 
When you do 'select * from @table', it expects a table variable. Try something like this:

Code:
set @table = 'dbo.AUDIT2' + @YR  

declare @sql varchar(100)
set @sql = 'select * from ' + @table

exec(@sql)

Hope it helps,

Alex

Ignorance of certain subjects is a great part of wisdom
 
is there any other way other than Dynamic SQL? By the thanks for your help.
 
I think that you might be out of luck. You could simply hard-code the full table name with the year included, and adjust your proc each year, but who wants to do that?

Sorry,

Alex

Ignorance of certain subjects is a great part of wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top