动态数据库名称和存储列值为变量

时间:2012-09-17 10:52:41

标签: sql-server sql-server-2008

我正在使用SQL Server 2008.我的存储过程必须传递动态数据库名称并将列值存储到变量中

ALTER PROCEDURE [dbo].[proc_testproc](@mUserId int)
AS
declare @logCreate BIT;
declare @dbname sysname;
set @dbname = 'finaldb'

exec('SELECT ua.LogCreate AS ' + @logCreate + ' from '+ @dbname
   + 'dbo.User_Access as ua where ua.UserId=' + @mUserId + ')

IF @logCreate = 1 
--- Below some insertion happens based on the select query output--

任何人都可以帮助我如何传递动态数据库名称并将值存储到变量中吗?

1 个答案:

答案 0 :(得分:1)

您需要的成分是

基本上,构建一个使用sp_executeSQL运行的动态SQL语句,并将变量传递给它。将变量声明为OUTPUT参数,它可以将结果带出动态SQL语句。

ALTER PROCEDURE [dbo].[proc_testproc](@mUserId int)
AS
declare @logCreate BIT;
declare @dbname sysname;
set @dbname = 'finaldb'

declare @sql nvarchar(max)
set @sql = '
    SELECT @logCreate=ua.LogCreate
    from '+ @dbname + '.dbo.User_Access as ua
    where ua.UserId=@mUserId'
exec sp_executesql @sql,
    N'@logCreate BIT output,@mUserId int',
    @logCreate output, @mUserId

IF @logCreate = 1