3

当我运行以下代码时,我收到“无效的对象名称”错误,知道为什么吗?

我需要创建一个动态命名的临时表以在存储过程中使用。

 DECLARE @SQL NVARCHAR(MAX)
 DECLARE @SessionID NVARCHAR(50)
 SET @SessionID = 'tmp5l7g9q3l1h1n5s4k9k7e'
 ;
 SET        
 @SQL = N'      CREATE TABLE #' + @SessionID + ' ' +
         N'     (' +
    N'      CustomerNo NVARCHAR(5), ' +
    N'      Product NVARCHAR(3), ' + 
    N'      Gross DECIMAL(18,8) ' +
    N'      )'
 ;
 EXECUTE sp_executesql @SQL
 ;
 SET        
 @SQL = N'      SELECT * FROM #' + @SessionID
 ;
 EXECUTE sp_executesql @SQL

谢谢!

4

3 回答 3

3

为什么要乱用名字?让 SQL Server 为您管理:

SQL Server 中的临时表

从上面的链接:

If the same routine is executed simultaneously by several processes, the Database Engine needs to be able to distinguish between the identically-named local temporary tables created by the different processes. It does this by adding a numeric string to each local temporary table name left-padded by underscore characters. Although you specify the short name such as #MyTempTable, what is actually stored in TempDB is made up of the table name specified in the CREATE TABLE statement and the suffix. Because of this suffix, local temporary table names must be 116 characters or less.

If you’re interested in seeing what is going on, you can view the tables in TempDB just the same way you would any other table. You can even use sp_help work on temporary tables only if you invoke them from TempDB.

USE TempDB
go
execute sp_Help #mytemp 

or you can find them in the system views of TempDB without swithching databases.

SELECT name, create_date FROM TempDB.sys.tables WHERE name LIKE '#%'
于 2012-05-02T17:16:31.180 回答
1

你这样做是不对的!

尝试:

exec(@SQL)

代替:

EXECUTE sp_executesql @SQL

要使用sp_executesql变量必须在@SessionID引号内,并且必须提供输入参数。检查以获取完整示例!


你必须知道动态 SQL 是一个很好的 SQL 注入端口!

于 2012-05-02T15:47:48.293 回答
1

此语法有效

CREATE TABLE #SessionID (CustomerNo NVARCHAR(5),  Product NVARCHAR(3),  Gross DECIMAL(18,8));
Select COUNT(*) from #SessionID;
Drop Table #SessionID;
于 2012-05-02T16:30:25.667 回答