简体   繁体   中英

How to pass database name into stored procedure?

How to pass database name into stored procedure? I tried something like

create procedure dbo.Test
    @databaseName varchar(100)
as
select * from @databasename.Person.Address
go

I would like to use it like this

execute dbo.Test @databaseName = 'AdventureWorks'

This is not possible in the manner you are describing.

You can do this with dynamic SQL , but that brings its own set of problems.

Sounds like you are trying to move information which should be part of connection string into stored procedure logic. If you expect that Person table will be in different database this database name should be fixed in deployment - for example by parametrized creation script and sqlcmd.

Yeah you'd have to do some dynamic sql. While this article doesn't explicitly go into dynamic sql creation, it should be enough to get you started: http://www.relationalis.com/articles/2011/4/17/dealing-with-quotes-in-sql.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM