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 2008 Forums
 Transact-SQL (2008)
 change the database name in aquery via paramter?

Author  Topic 

akpaga
Constraint Violating Yak Guru

331 Posts

Posted - 2013-08-12 : 11:48:43
Hi friends

I have following query populating a report on front end

select * from Customers.customer_name cn
join Houston.Customer_address ca
on cn.id=cd.ID

The front end report now should have a city parameter and whenever the city is chosen

the query should change like this say -the city chosen is Dallas
select * from Customers.customer_name cn
join Dallas.Customer_address ca
on cn.id=cd.ID

i.e the database now has been changed to Dallas.Customer_Address..

Can this be done using case statements? Please explain..Thank You


James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-12 : 11:59:48
It probably is possible, but not easy, clean, or recommended. The reason for that is that the database design is not sound. Naming tables based on data can lead to all kinds of problems.

Ideally you should create a single table for customers with multiple columns, one for a customer_id, others for firstname, lastname, address, city, zip code etc. You can further normalize it if you wish by having a Cities table and referring to that table in the city column of the customers table.
Go to Top of Page

denis_the_thief
Aged Yak Warrior

596 Posts

Posted - 2013-08-12 : 12:11:56
Your design does look worrysome.

But to answer your question, you could acheive this with Dynamic SQL.
Go to Top of Page
   

- Advertisement -