Click here to Skip to main content
15,891,621 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
i Have many datatabase such as :
- BR_1
- BR_2
- BR_3
- .....

and i want to select Table.Students from all of that databases
without select one by one :

SELECT * FROM BR_1.dbo.Students
SELECT * FROM BR_2.dbo.Students
SELECT * FROM BR_3.dbo.Students
Posted
Updated 22-Jan-15 15:46pm
v3
Comments
PIEBALDconsult 22-Jan-15 20:28pm    
Union?
ZurdoDev 22-Jan-15 22:15pm    
I suggest you post as solution.
phanithly 22-Jan-15 21:46pm    
no , i don't mean that
ZurdoDev 22-Jan-15 22:15pm    
1. Reply to the comment so that the user is notified instead of adding a new comment to your own question.
2. A union is the correct answer.

1 solution

try to create stored procedure,
1. first you need to search tables in the databases with matching name,for example

SQL
sp_MSforeachdb 'SELECT "?" AS DB, * FROM [?].sys.tables WHERE name like ''Students'''

find you the databases where Students contains. refer Find a Table on a SQL Server across all Databases[^]

2. Now you need to build union sql statement based on above database and table values in your stored procedure. for example if you have BR_1, BR_2, your sql string will be

SQL
SELECT * FROM BR_1.dbo.Students
union
SELECT * FROM BR_2.dbo.Students


3. finally execute the dynamically created sql statement and fetch the data
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900