0

I have ten to twenty databases in my server. Everytime i need to query i want to put something like this

Select *  from otp-devices.dbo.deviceid 
select module from mr1ghp/security.dbo.alarmmodlink

Our database names are long . Is it possible to shorten or alias database name in query otp-devices mr1ghp/security

Bodhi
  • 548
  • 4
  • 14
  • 26

3 Answers3

2

You can make an alias with the keyword AS like this :

SELECT * FROM `otp-devices.dbo.deviceid ` AS otp
Arrabidas92
  • 1,113
  • 1
  • 9
  • 20
  • This is true for one query. but I have seen a way to do it from the database level itself. that is we can use that name for our database name in anywhere in our sql server. – Bodhi Oct 14 '17 at 13:28
  • @coffemug there isn’t anything like that in SQL Server. Except possibly sqlcmd variables. – Martin Smith Oct 14 '17 at 14:35
1

Since SQL Server 2008, SQL Server has supported synonyms.

You can read about the syntax here.

You can read about the ideas here.

I'm not really a fan of synonyms. I find databases harder to navigate when the same object has different names in different places -- and I cannot readily see the mapping (as with aliases in a single query).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

Another possibility is to use views to provide the link to tables in other databases. Use naming conventions to identify which database the view is linked to. This also helps to insulate the code from any changes to database names.

CREATE VIEW vOD_deviceid AS SELECT * FROM [otp-devices].dbo.deviceid ;

and

CREATE VIEW vSC_alarmmodlink AS SELECT * FROM mr1ghp/security.dbo.alarmmodlink

Then elsewhere

SELECT * FROM vOD_deviceid; -- OD prefix identifies the database
SELECT module FROM vSC_alarmmodlink;

Just substitute the view name wherever you would have used the full database.schema.tablename.

JohnRC
  • 1,251
  • 1
  • 11
  • 12
  • This can be done for repetitive queries, and i do have some views for the purpose but most of the time our requirement changes and we dont have a particular query for our purpose – Bodhi Oct 14 '17 at 19:28
  • I mean that once you have defined the baseline view of the table, then you always use the view instead of referring directly to the table - even in other views. So the view is the single local representation of the table in the other database. You don't create a different view for every query you have, that would defeat the objective. – JohnRC Oct 16 '17 at 12:03