문제

I have multiple databases. Can I hit one of the databases based on an identifier which is dynamic? e.g. I have three databases DB1,DB2,DB3.

I have a query select * from tblEmployees.(This table is present in all the three DBs). I have an identifier(or some variable ) whose value can be 1 or 2 or 3 and based on the value of this variable which I get dynamically when my service is hit, I would like to choose the DB from which the values should be obtained.

Can this be done? My DB is SQL Server and front end is asp.net.

My connection strings are stored in web.config file. Can I have multiple connection string which will have the same server with diff db names and select one of them based on the identifier.

도움이 되었습니까?

해결책

1.In real world most of the time you have to store your connection strings in your web.config file . so there you can let's keep three connection strings which will have the same server but different databases name, then you can select one of the connection-string for your app connection to the required database.

2.you can build that connection string on run-time if you need.

using these technique you will never have to write 2 or more queries just change the query string and your queries will work for all the databases.

다른 팁

You can do like this

if(val == 1)
{
  select * from [DB1].[dbo].[tblEmployees]
}
else if(val == 2)
{
  select * from [DB2].[dbo].[tblEmployees]
}

Try this one -

DECLARE @ID INT
SELECT @ID = 2

DECLARE @SQL NVARCHAR(500)
SELECT @SQL = 'SELECT * FROM DB' + CAST(@ID AS CHAR(1)) + '.dbo.tblEmployees'

PRINT @SQL
EXEC sys.sp_executesql @SQL

Output -

SELECT * FROM DB2.dbo.tblEmployees

T-SQL way:

declare @db int


if @db = 1
begin

    use [db1]
    select *
    from tblEmployees

end

if @db = 2
begin
    use [db2]
    select *
    from tblEmployees
end

-- and so on

IMO you're best bet would be to use a different connection-string to achieve multi-tenency against similar alike databases. Ideally, abstracted away behind some code so that most of your code doesn't need to know about it, but just does:

using(var conn = Somewhere.GetOpenConnection()) {
    // ...
}

or worst-case:

using(var conn = Somewhere.GetOpenConnection(Environment.Published)) {
    // ...
}

(here Environment is an enum to what the various databases represent)

where GetOpenConnection figures out which database is needed, and either looks up on constructs the correct connection string.

But to be specific:

  • you cannot parameterize the DB name in a query
  • using use between operations would be a really bad idea in terms of connection re-use
  • you can explicitly use three-part identifiers (i.e. DB1..SomeTable or DB1.dbo.SomeTable), but that does not scale naturally to lots of databases
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top