如何将变量值和select语句的结果一起放入sql表?

时间:2019-07-01 18:31:55

标签: sql sql-server

我正在尝试将SQL select语句的结果插入到表中,并与FETCH循环内的SQL变量中的值一起。我只能对选择结果进行插入,但是无法弄清楚如何将变量值与之一起插入。

这是我尝试过的:

IF CURSOR_STATUS('global','CURSOR_ALLDB_NAMES')>=-1
BEGIN
 DEALLOCATE CURSOR_ALLDB_NAMES
END
IF OBJECT_ID('tempdb..#TempIDs') IS NOT NULL DROP TABLE #TempIDs

CREATE TABLE #TempIDs(
 ID char(256)
 ,DBName char(256))

DECLARE @DB_NAME nvarchar(256);

DECLARE CURSOR_ALLDB_NAMES CURSOR FOR
SELECT name 
FROM Sys.Databases
WHERE name like 'ZM_%' 

OPEN CURSOR_ALLDB_NAMES

FETCH CURSOR_ALLDB_NAMES INTO @DB_NAME

WHILE @@Fetch_Status = 0
BEGIN
--  if  OBJECT_ID(@DB_NAME + '.dbo.Userlist') is not null   EXEC('Insert into #TempIDs (ID) Select ID from '+ @DB_NAME + '.dbo.Userlist')
  if  OBJECT_ID(@DB_NAME + '.dbo.Userlist') is not null   EXEC('Insert into #TempIDs (ID, DBName) Select ID, @DB_NAME from '+ @DB_NAME + '.dbo.Userlist')
  FETCH CURSOR_ALLDB_NAMES  INTO @DB_NAME
END

Select * from #TempIDs

我得到这个结果:

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@DB_NAME".

我也尝试了这种方法,但没有用:

if  OBJECT_ID(@DB_NAME + '.dbo.Userlist') is not null   EXEC('Insert into #TempIDs (ID, set DBName=''' +@DB_NAME + ''') Select ID  from '+ @DB_NAME + '.dbo.Userlist')
  FETCH CURSOR_ALLDB_NAMES  INTO @DB_NAME

这也行不通:

if  OBJECT_ID(@DB_NAME + '.dbo.Userlist') is not null   EXEC('Insert into #TempIDs (ID, DBName=''' +@DB_NAME + ''') Select ID  from '+ @DB_NAME + '.dbo.Userlist')
  FETCH CURSOR_ALLDB_NAMES  INTO @DB_NAME

1 个答案:

答案 0 :(得分:0)

感谢@JNevil的评论:

更改SQL语句。此行已更改,现在可以使用:

  if OBJECT_ID(@DB_NAME + '.dbo.Userlist') is not null EXEC('Insert into #TempIDs (ID, DBName) Select ID, ''' + @DB_NAME + ''' from ' + @DB_NAME + '.dbo.Userlist')