声明临时表并插入查询中

时间:2017-05-18 02:12:02

标签: sql sql-server

我尝试在我的查询中调用declare temp table但它说

“必须声明表变量”@MDLTable“。”

这是我的编码:

DECLARE @dbname AS NVARCHAR(50);
SELECT @dbname = DB_NAME(); 
PRINT @dbname;
DECLARE @sql NVARCHAR(1000) ;
DECLARE @MDLTable AS TABLE(MDLID BIGINT, MDLRLVR INT)

SET @sql = 'INSERT INTO ' + @MDLTable + ' (MDLID, MDLRLVR) 
SELECT DISTINCT a.MDLID, a.MDLRLVR FROM ' + @dbname + '.dbo.EUSYSRSRRL a 
INNER JOIN  ' + @dbname + '.dbo.EUSYSIROE b ON a.MDLID = b.MDLID 
INNER JOIN ' + @dbname + '.dbo.EUSYSEAPML c ON b.EAPMLID = c.EAPMLID 
WHERE c.REEID = ' + CONVERT(nvarchar(50),6) + ''
exec (@sql);

1 个答案:

答案 0 :(得分:1)

您可以使用SET @sql = ' SELECT DISTINCT a.MDLID, a.MDLRLVR FROM ' + @dbname + '.dbo.EUSYSRSRRL a JOIN ' + @dbname + '.dbo.EUSYSIROE b ON a.MDLID = b.MDLID JOIN ' + @dbname + '.dbo.EUSYSEAPML c ON b.EAPMLID = c.EAPMLID WHERE c.REEID = ' + CONVERT(nvarchar(50), 6) + ''; INSERT INTO @MDLTable (MDLID, MDLRLVR) exec(@sql);

执行此操作
{{1}}