我不会从一组表对中创建两个不同的临时表,这些表对在至少两个不同的数据库中具有相同的表名。总的来说,我有4对不同的表对,这就是为什么我尝试为其声明变量的原因,所以我只需要在程序顶部更改表名。
当我尝试声明用于“发件人”语句中的变量但无法使代码正常工作时。我已经阅读了一些有关动态编程的文章,但并不太了解如何在这种情况下使用它。
DECLARE @table char(20);
SET @table = 'Table_1';
SELECT a.*
into #temp1
FROM [DB_1].[Schema].@table a
select a.*
into #temp2
FROM [DB_2].[Schema].@table a
预先感谢
欢呼
答案 0 :(得分:0)
我只是将Adventure Works示例数据库用作示例数据库,请使用此sql脚本,它将满足您的预期结果
IF OBJECT_ID('tempdb..#TableList')IS NOT NULL
DROP TABLE #TableList
CREATE TABLE #TableList(
Id INT IDENTITY,
TABLE_NAME VARCHAR(100),
TABLE_CATALOG VARCHAR(100),
TABLE_SCHEMA VARCHAR(100),
TempTableNAme VARCHAR(100)
)
INSERT INTO #TableList
(TABLE_NAME,
TABLE_CATALOG,
TABLE_SCHEMA,
TempTableNAme
)
SELECT TABLE_NAME ,
TABLE_CATALOG ,
TABLE_SCHEMA,
'#Temp'+CAST(ROW_NUMBER()OVER(ORDER BY TABLE_NAME) AS VARCHAR(10)) AS TempTableNAme
FROM INFORMATION_SCHEMA.TABLES
ORDER BY 1
DECLARE @MaxID INT,
@MinID INT,
@Sql nvarchar(max),
@GetTABLE_NAME VARCHAR(100),
@GetTABLE_CATALOG VARCHAR(100),
@GetTABLE_SCHEMA VARCHAR(100),
@GetTempTableNAme VARCHAR(100)
SELECT @MaxID=Max(Id),@MinID=Min(Id)
FROM #TableList
WHILE @MinID<=@MaxID
BEGIN
SELECT @GetTABLE_NAME= TABLE_NAME ,
@GetTABLE_CATALOG =TABLE_CATALOG,
@GetTABLE_SCHEMA=TABLE_SCHEMA,
@GetTempTableNAme=TempTableNAme
FROM #TableList WHERE Id = @MinID
SET @Sql='SELECT * INTO '+@GetTempTableNAme+'_'+@GetTABLE_NAME+' FROM '+ QUOTENAME(@GetTABLE_CATALOG) +'.'+ QUOTENAME(@GetTABLE_SCHEMA)+'.'+ QUOTENAME(@GetTABLE_NAME)
--EXEC (@Sql)
PRINT @Sql
SET @MinID=@MinID+1
END
答案 1 :(得分:-1)
您可以为此使用动态SQL:
DECLARE @table char(20);
SET @table = 'Table_1';
SET @SQL = 'SELECT a.* into #temp1 FROM [DB_1].[Schema].' + @table + 'a'
SET @SQL2 = 'select a.* into #temp2 FROM [DB_2].[Schema].' + @table + 'a'
EXEC(@SQL);
EXEC(@SQL2);