Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing DB Name as a Parameter to Stored Proc

Status
Not open for further replies.

vness

MIS
Joined
Nov 22, 2002
Messages
4
Location
US
Is it possible to pass a database name into a stored procedure as variable to fully qualify an object?

For example:

CREATE PROCEDURE [dbo].[Test_SP]

@p2 as nvarchar(10)

AS

SELECT DISTINCT @p2.dbo.Objects.Col1, @p2.dbo.Objects.Col3, @p2.dbo.Objects.Col4, @p2.dbo.Objects.ID

FROM @p2.dbo.Objects INNER JOIN @p2.dbo.Structure ON @p2.dbo.Objects.ID = @p2.dbo.Structure.ID

WHERE (@p2.dbo.Structure.Col7 = 4 )
GO
 
Hi,

u will have to use Dynamic SQL to do that....


CREATE PROCEDURE [dbo].[Test_SP]

@p2 as nvarchar(10)

AS
Declare @SQL varchar(2000)

SET @SQL = 'SELECT DISTINCT ' + @p2 + '.dbo.Objects.Col1, ' + @p2 + '.dbo.Objects.Col3, ' + @p2+ '.dbo.Objects.Col4, ' + @p2 + '.dbo.Objects.ID

FROM ' + @p2 + ' .dbo.Objects INNER JOIN ' + @p2 + ' .dbo.Structure ON ' + @p2 + '.dbo.Objects.ID = ' + @p2 + '.dbo.Structure.ID
WHERE (' + @p2 + '.dbo.Structure.Col7 = 4 )'

Exec(@SQL)
GO


Hope it helps

Sunil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top