troubleshooting Question

1 query/SP multiple databases

Avatar of davism
davismFlag for United States of America asked on
DatabasesMicrosoft SQL ServerSQL
7 Comments1 Solution108 ViewsLast Modified:
We have some database that like span different states.

We have code for a stored procedure and that stored procedure resides in a Stage database on the same server so a linked server is not necessary.

CREATE PROCEDURE dbo.TestA
(@StateID CHAR(2))
AS
BEGIN 

   SET NOCOUNT ON


  UPDATE dbo.TableA

       SET MemTypeInd='Y'

  WHERE State=@State


END


As you see in this store procedure updates dbo.TableA. Yet, there could be let's say 14 states that have this. So basically there is 1 aspect of code which is in a stage database that needs to run for each. So I basically could not even use a dbo.TableA being that the SP is on a stage database.

What I would need is something like:

CREATE PROCEDURE dbo.TestA
(@StateID CHAR(2))
AS
BEGIN 

   SET NOCOUNT ON


  UPDATE StateFL.dbo.TableA

       SET MemTypeInd='Y'

  WHERE State=@State


END

CREATE PROCEDURE dbo.TestA
(@StateID CHAR(2))
AS
BEGIN 

   SET NOCOUNT ON


  UPDATE StateCO.dbo.TableA

       SET MemTypeInd='Y'

  WHERE State=@State


END

Or basically leave it as dbo.TableA but yet still reside on the stage DB.  Or even like a @DBName.dbo.TableA where the @DBName would equate to like the StateFL or StateCO.

I know there is the sp_MSforeachdb but that would basically be like a dynamic SQL as well.    

What other possible ways are there to achieve this without a dynamic sql as a dynamic sql does not take the best query path with the sql optimizer unless that has changed which I do not think it did.
ASKER CERTIFIED SOLUTION
Bitsqueezer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros