2013-09-25 61 views
1

我有下面的代碼片段:填充與動態變化的數據從另一個數據庫

DECLARE @uidSecurity NVARCHAR(25), 
     @sql NVARCHAR(500), 
     @DBName nvarchar(50)= 'DBNAME', 
     @SecurityGroup nvarchar(10) = 'NEWGROUP' 

    declare @Winlogon table (
    uidFileNumber nvarchar(25)) 

    select @sql = ' INSERT INTO @Winlogon 
     SELECT uidFileNumber 
     FROM [' + @DBName + '].dbo.SERCURE 
     WHERE code = ''' + @SecurityGroup + '''' 

    exec sp_executesql @sql 

    SELECT uidFileNumber FROM @WINLOGON 

我試圖從另一個數據庫將與代碼的每個循環改變填充數據的局部變量。我的問題是它不能識別在@SQL語句內聲明的@winlogon表變量。有沒有另一種方式可以做到這一點?

它的工作原理,如果我通過一個靜態的數據庫名稱到代碼如下:

DECLARE @uidSecurity NVARCHAR(25), 
    @sql NVARCHAR(500), 
    @sql1 NVARCHAR(500), 
    @SecurityGroup nvarchar(10) = 'NEWGROUP' 

    declare @Winlogon table (
    uidFileNumber nvarchar(25)) 

    INSERT INTO @Winlogon 
    SELECT uidFileNumber 
    FROM [STATICDB].dbo.SERCURE 
    WHERE code = @SecurityGroup 

    SELECT uidFileNumber FROM @WINLOGON 

但我需要通過另一個局部變量每次通過不同的數據庫名稱代碼運行while循環。

回答

0

您可以使用INSERT-EXEC:

DECLARE @uidSecurity NVARCHAR(25), 
    @sql NVARCHAR(500), 
    @sql1 NVARCHAR(500), 
    @SecurityGroup nvarchar(10) = 'NEWGROUP' 

DECLARE @Winlogon TABLE (
    uidFileNumber nvarchar(25)) 

SET @sql = N'SELECT uidFileNumber 
    FROM ' + QUOTENAME(@DBName) + '.dbo.SERCURE 
    WHERE code = ' + QUOTENAME(@SecurityGroup, '''') 

INSERT INTO @Winlogon(uidFileNumber) 
EXEC(@sql)