SQL - Add database name to FROM clause

Dear Experts,

I have some queries which needs to be created as a Stored Procedure but also by that changing to contain the database information after the FROM clause.

Briefly for example query in such format:
SELECT TOP 10
	AD.LFA1.LIFNR
FROM
	AD.LFA1

Open in new window


will be need to be re-formatted as (SAP_DATA added so the database name):

SELECT TOP 10
	AD.LFA1.LIFNR
FROM
	SAP_DATA.AD.LFA1

Open in new window


Could you please advise regarding the best practice, how to add database information to the FROM clause relatively easily?

Actually my only idea is to replace text 'AD.' with 'SAP_DATA.AD.'  in Excel in the code

Thanks in advance,
LVL 1
csehzIT consultantAsked:
Who is Participating?
 
Mark WillsTopic AdvisorCommented:
In a stored procedure you could create dynamic SQL.

You would need to pass in the DB name to your stored proc

Declare @Dsql  varchar (800)
Set @Dsql = '
SELECT TOP 10
	A.LIFNR
FROM
	'+@dbname+'.AD.LFA1 as A'

exec (@Dsql)

Open in new window


And you pass in the value of  @dbname as a parameter.....

And use Alias on your table name 'AS A' so thats what you then refer to in your select 'A.LFNR'

But your situation does need to warrant the use of dynamic SQL - it will need some checking and error handling...
0
 
ste5anSenior DeveloperCommented:
Why? Cause both queries are not equivalent..
0
 
Ganesh GuruduSenior ConsultantCommented:
if you have very less number of Procedure then its okay to change/replace the code with "SAP_DATA.AD." from "AD."

IF you have more DB objects you just need to provide the access to AD DB/Schema from SAP_DATA. Or Create DB link for the same.
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
Actually my only idea is to replace text 'AD.' with 'SAP_DATA.AD.'  in Excel in the code
This will work if SAP_DATA database exists in the same SQL Server instance.
0
 
csehzIT consultantAuthor Commented:
Thank you for the advices, finding them as interesting alternatives
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.