0

I have following situation:

Input parameter in stored procedure is database name. So, depends on this parameter query is executed on different database. Every query is same, below is only simple example.

How to write stored procedure (except using dynamic sql) to avoid IF...ELSE statement like in code bellow.

ALTER PROCEDURE [dbo].[usp_Item_GetAll]
(
    @DBName nvarchar(255) = ''  
)
AS
BEGIN

IF @DBName = 'ItemUsers'
BEGIN
    SELECT
    *
    FROM ItemUsers.dbo.vW_DAM_ItemWithAttribute
END

ELSE IF @DBName = 'CollectionUsers'
BEGIN
    SELECT
        *
    FROM CollectionUsers.dbo.vW_DAM_ItemWithAttribute
END
1
  • 1
    I don't think there is another way besides dynamic sql and what you have done here. Commented Jul 2, 2013 at 21:01

1 Answer 1

0

You may create a string that contains the dynamic query along with database name and then execute that query using EXEC command something like this

ALTER PROCEDURE [dbo].[usp_Item_GetAll]
(
    @DBName nvarchar(255) = ''  
)
AS
BEGIN

DECLARE @SQL varchar(MAX)
SET @SQL='SELECT * FROM ['+@DBName+'].dbo.[vW_DAM_ItemWithAttribute]'
EXEC(@SQL)
END
Sign up to request clarification or add additional context in comments.

1 Comment

I would use QUOTENAME() instead of manually putting square brackets around it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.