December 20, 2007 at 8:16 am
ALTER Procedure lookupemp
@dbname varchar(30),@UserName varchar(10)
as
begin
set nocount on
declare @SQLCmd nvarchar(4000)
set @SQLCmd = 'use ' + @DBName + ';
select jobid,empname from tblemp where user=@username
'
exec sp_executesql @SQLCmd,N'@UserName varchar(4)',@UserName
end
Like the Proc above can do the same thing for a view, I understand we cant pass paramters to view but how can i achieve a dynamic view so that by passing db name as paramter i can access view from any db.
December 20, 2007 at 8:42 am
You cannot make a dynamic view.
You can make the same view in every db and then call it with the 3 part naming (db.owner.view).
So I can create MyView in every database and just use my database name as the parameter.
select * from Northwind.dbo.MyView
select * from Pubs.dbo.MyView
select * from AdventureWorks.dbo.MyView
December 20, 2007 at 3:05 pm
Can I make a view as table valued function so that I can run the view in any db by passing the database name as parameter. something like this....
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION Employee
(
@dbname varchar(30)
)
RETURNS TABLE
AS
RETURN
declare @SQLCmd nvarchar(4000)
set @SQLCmd = 'use ' + @DBName + ';
select empno,name,jobid,jobname from tblemp
where satus=''A''
'
EXEC(SQLCmd)
GO
I am sure there shud be some syntax error, please shed some light on making a view dynamic by hook or crook.
thanks
December 20, 2007 at 3:19 pm
Dynamic SQL is not allowed inside of functions.
_____________
Code for TallyGenerator
December 20, 2007 at 3:38 pm
I am sure table valued function will allow parameters but why cant we pass dbname as parameter and execute it from any where in same server
December 21, 2007 at 6:46 am
so there is no way to run a view from any database?
is it possible by using master db?
December 21, 2007 at 8:35 am
Yes, it is possible... read the following article... because these are a bit "tricky", make sure that you read and understand the entire article before you try anything like that...
http://www.sqlservercentral.com/articles/Administering/utilityprocedures/2272/
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply