Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a TSQL function database name

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 ...
like image 954
Hell.Bent Avatar asked Sep 27 '26 07:09

Hell.Bent


1 Answers

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:

  1. @DatabaseName is the passed as parameter to your procedure.

  2. @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

like image 81
gotqn Avatar answered Sep 30 '26 03:09

gotqn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!