Monday, 9 March 2015

Select data from after consolidating tables' name

I have experienced a situation where part of the table name is stored in another table. All the tables in the databases have same prefix but remaining name part concatenates and creates the name of the table. However the nature of the application behaves it stores the suffix of the table name in a separate table. If i need to retrieve data from a table which is stored in another table which has only the  suffix , what i did was i concatenated the table prefix and suffix to select out data.

This is how i did it. I used EXEC command to run the select query.

tbl_FormDATA 
ID
Reference
Formname
1
112852
Customer
2
125369
Shopper

tbl_Customer
ID
Name
Address
1
Test
Test Address

tbl_Shopper
ID
Shop No
1
10-1


DECLARE @tble varchar(100);

SELECT @tble ='tbl_'+FormName
FROM tbl_FormDATA
WHERE reference = 112852;
EXEC('select * from ' + @tble);

No comments:

Post a Comment