开发者

Dynamically Select from different DB's based on input to sproc

开发者 https://www.devze.com 2023-04-11 03:53 出处:网络
I\'m trying to alter a stored procedure in our DB from a hard-coded select from 1 specific DB to be able to select from any of our DB\'s based on an id that\'s passed into the sproc. Here\'s the stub

I'm trying to alter a stored procedure in our DB from a hard-coded select from 1 specific DB to be able to select from any of our DB's based on an id that's passed into the sproc. Here's the stub of what the sproc is doing for us:

ALTER PROCEDURE [dbo].[GetByAdId]
(
@AdId int,
@UserCompanyId int
)
AS
SET NOCOUNT ON

SELECT  
    [User].[UserId],
    UserMappings.IsActive,
    IsAccountOwner = ( SELECT Count(*) FROM DB1_SetUp.dbo.ad Adv WHERE Adv.AdI开发者_JAVA技巧D = UserMappings.AdID AND Adv.PrimaryAccountOwnerID = [User].[UserId] )
FROM   
    [User] INNER JOIN UserMappings ON 
    (
        UserMappings.UserID = [User].UserID
        AND UserMappings.AdID = @AdId
        AND UserMappings.UserCompanyId = @UserCompanyId 
    )

Basically the "IsAccountOwner" variable is hardcoded to select from DB1_SetUp every time, but we have a number of SetUp db's for different groups, so like DB2_SetUp, DB3_SetUp, etc. The UserCompanyId variable being passed into the sproc functions like a group Id and can be used to point to the particular SetUp DB I want it to select from, but I'm not sure how to do this. I basically wanted something on the ilk of:

SELECT * FROM (
    CASE @UserCompanyId
        WHEN 3 THEN 'DB3_SetUp'
        WHEN 4 THEN 'DB4_SetUp'
)

Is there a clean way to do this, or will I have to setup this sproc on each group DB and call the specific one over on each DB?


I've done this in the past by dynamically building the SQL I wanted to execute (based on parameters passed in) and then executing the SQL using sp_executesql

see: http://msdn.microsoft.com/en-us/library/ms188001.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消