日期:2014-05-17  浏览次数:20921 次

insert into select如何插入变量?
我想写一个遍历数据库并统计出所有表及其包含的记录数,代码如下,但是在插入时遇到了问题,insert into语句把@TableName当做了列名,而我的本意是一个变量。我该怎么做呢?静候各位大侠的回音!谢啦!
SQL code
use Tfs_Test
 DECLARE @TableName varchar(255);
 CREATE TABLE #TempTable([id] [INT] IDENTITY(1,1) NOT NULL, [TableName] varchar(255) NOT NULL, [RecordingCount] INT);
DECLARE Table_Cursor CURSOR FOR SELECT [name] FROM sysobjects WHERE xtype='U';
 OPEN Table_Cursor;
 FETCH NEXT FROM Table_Cursor INTO @TableName;
  WHILE(@@FETCH_STATUS=0)
BEGIN
EXEC('INSERT INTO #TempTable ([TableName],[RecordingCount]) SELECT '+@TableName+', COUNT(0) FROM ['+@TableName+'];');
 FETCH NEXT FROM   Table_Cursor INTO @TableName;
END
CLOSE Table_Cursor;
 DEALLOCATE Table_Cursor;
SELECT [TableName] AS [表名称],[RecordingCount] AS [总记录数] FROM #GetRecordingTempTable ORDER BY [RecordingCount] DESC;
DROP TABLE #TempTable;
 GO


------解决方案--------------------
你那个exec的改成这样看看:
SQL code
INSERT INTO #TempTable ([TableName],[RecordingCount])
EXEC(' SELECT '+@TableName+', COUNT(0) FROM ['+@TableName+'];');

------解决方案--------------------
这样
SQL code

EXEC('INSERT INTO #TempTable ([TableName],[RecordingCount]) SELECT '''+@TableName+''', COUNT(0) FROM ['+@TableName+'];');