views:

32

answers:

1

I have a stored procedure which gets data from another database on the same server.

I will not be hard-coding which database to use, instead this will be configurable. Is this possible without dynamic sql?

The best solution I could come up with so far is to first run a stored procedure which uses dynamic sql to generate a bunch of views. I can then select data from these views to avoid using dynamic SQL for everything.

Example:

DECLARE 
    @databaseName nvarchar(max),
    @sql          nvarchar(max)

-- Get this value from a configuration table
SET @databaseName = 'TestDatabase'

IF EXISTS(SELECT NULL FROM dbo.SysObjects WHERE [Name] = 'TestView')
    DROP VIEW dbo.TestView

SET @sql = 'CREATE VIEW dbo.TestView AS SELECT * FROM ' + @databaseName +'.dbo.TestTable'

EXEC (@sql)

--I can now select from TestView using regular query.

I'm guessing that I'm going about this the wrong way. Is there a better way to do this?

+1  A: 

You can use

OPENQUERY or OPENROWSET

Pranay Rana
Thanks for this. Both those options are very interesting, however they still rely on building a sql string.
Evil Pigeon
Then do please tell us why you're opposed to that.
Tobiasopdenbrouw
Bugs are more easily introduced and harder to debug with dynamic SQL. I could write a stored proc with random nonsense in a SQL string, and I won't know about the problem until I tried to run it.
Evil Pigeon