Link to home
Start Free TrialLog in
Avatar of RadhaKrishnaKiJaya
RadhaKrishnaKiJaya

asked on

Variables in SQL

Hello Experts,
Can I use variable file name in sql statement? For example Select *From @Variable_File_Name?  Thank you very much in advance.

Thank you!
Avatar of Jeff Darling
Jeff Darling
Flag of United States of America image

-- Create a table Variable
DECLARE @myTable TABLE (
	FirstName varchar(30)
	,LastName varchar(30)
	);
	
	
-- add some records to @myTable
Insert into @myTable (FirstName,Lastname) values  ('John','Smith') 
Insert into @myTable (FirstName,Lastname) values  ('Jane','Doe') 
Insert into @myTable (FirstName,Lastname) values  ('Homer','Simpson') 

-- Query Table Variable
Select * from @myTable

Open in new window

SOLUTION
Avatar of OriNetworks
OriNetworks

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RadhaKrishnaKiJaya
RadhaKrishnaKiJaya

ASKER

Hi Jeff Darling,  Thank you for your help.

I have some tables like XX_2013, XX_2014, XX_2015 etc.  I want to select the table based on the @YEAR parameter passed.  It is not a new table I need to create, but need to select an existing one.

Thank you again!
You really can't do that in SQL Server.  SS doesn't allow variable object names.
To be honest, I believe your issue stems from bad design, especially if those tables are identical with data from different years.  They should really be one table with a year column.  Then querying it would be trivial.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OriNetworks,
Thank you for your help.  Please read my comments above and let me know if you think it would create any issue in future.

Thank you again!
Already described.