Is there any way to pass a tsql function a database name so it can perform selects on that database
ALTER function [dbo].[getemailjcp]
(
@DB_Name varchar(100)
)
Returns varchar(4000)
AS
BEGIN
DECLARE @out varchar (4000);
DECLARE @in varchar (1000);
Set @out =
(select substring
((select ';' + e.email from
(SELECT DISTINCT ISNULL(U.nvarchar4, 'NA') as email
FROM [@DB_Name].dbo.Lists ...
In order to create dynamic SQL statement you should store procedure. For example:
DECLARE @DynamicSQLStatement NVARCHAR(MAX)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @FirstID BIGINT
SET @ParmDefinition = N'@FirstID BIGINT OUTPUT'
SET @DynamicSQLStatement=N' SELECT @FirstID=MAX(ID) FROM ['+@DatabaseName+'].[dbo].[SourceTable]'
EXECUTE sp_executesql @DynamicSQLStatement,@ParmDefinition,@FirstID=@FirstID OUTPUT
SELECT @FirstID
In this example:
@DatabaseName is the passed as parameter to your procedure.
@FirstID is output parameter - this value might be return from your procedure.
Here you can find more information about "sp_executesql":
http://msdn.microsoft.com/en-us/library/ms188001.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With