有什么方法可以将数据库名称传递给sql函数,以便它可以对该数据库执行选择
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 ...
最佳答案
为了创建动态SQL语句,您应该存储过程。例如:
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
在此示例中:
在这里您可以找到有关“sp_executesql”的更多信息:
http://msdn.microsoft.com/en-us/library/ms188001.aspx