Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Database > SQL Language
|
SQL Language SQL Language discussions not specific to a particular RDBMS program or vendor.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the SQL Language section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old January 8th, 2007, 01:33 PM
Registered User
 
Join Date: Nov 2003
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Hadware Send a message via Yahoo to Hadware
Default Calling on a database within a stored procedure

Hi,
I am working with multiple databases on a server.
What I am attempting is to get data from two databases on one stored procedure.
Here is an example of what I'm trying to do:
create procedure sp_procedure
(
@variable int
)
declare @anothervariable char(3)
select @anothervariable = afield from atable where something = @variable
use dbo.@anothervariable
select anotherfield from anothertable where somethingelse = @variable

The afield column contains the database name.
What method within the stored procedure can I use to get to the other database?

Thanks,
Eric

 
Old January 8th, 2007, 05:11 PM
planoie's Avatar
Friend of Wrox
 
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts
Default

Usually, if you need to programmatically change a database/table/field within a query, you'd need to employ some sql command construction. Basically, the same way as you'd dynamically construct a query in program code, you need to construct the query within the stored procedure, then execute it. Use can use the EXEC(string) SQL function to execute constructed SQL.

Keep in mind, however, that dynamic SQL like this is inefficient and kind of defeats the pre-compiled sql benefit you get by having a stored procedure. Fortunately, you may only need to run the USE command dynamically if you only have to switch databases (and they all have the same schema).

-Peter





Similar Threads
Thread Thread Starter Forum Replies Last Post
calling stored procedure jomet JSP Basics 0 November 23rd, 2007 08:06 AM
Calling Stored Procedure Using vc++ senthil_mano Visual C++ 0 August 30th, 2006 12:20 AM
Calling Stored Procedure with parameters zarina_24 Classic ASP Professional 4 March 2nd, 2006 11:57 AM
VB calling DB2 stored procedure sangsri VB How-To 1 July 13th, 2005 08:55 AM
Calling an Oracle Stored Procedure booksnore2 BOOK: Professional SQL Server Reporting Services ISBN: 0-7645-6878-7 2 October 1st, 2004 09:35 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.