使用 SQL Server 在存储过程中通过选择查询创建具有唯一名称的临时表的语法

问题描述:

我想通过 SQL Server 存储过程中的选择查询创建具有唯一名称的临时表.

I want to create temp table with their unique name by a select query in a stored procedure in SQL Server.

例如:每当我运行选择查询时,要创建不同的临时表名称.

For example: whenever I run the select query at that time different temp table name want to create.

说得更清楚一点,我第一次运行选择查询时,临时表名称是temptable1,而第二次表名称是temptable2代码>等.

Let be more clear, at the first time when I will run the select query at that time temptable name is temptable1, while at the second time the table name will be temptable2 and so on.

我想知道在 SQL Server 的存储过程中执行选择查询和创建具有唯一名称的临时表的语法.

I want to know the syntax for executing the select query and creating the temptable with their unique name in a stored procedure in SQL Server.

在 SQL Server 存储过程的上下文中,引擎自行处理临时表的名称.

In the context of the SQL Server Stored Procedure, the engine is handling itself the names of the temporary tables.

如果多个用户同时执行同一个存储过程,则无需担心 - 临时对象无法在他们之间共享,不会发生冲突.

There is no need to worry if many users are executing the same stored procedure in same time - the temporary objects cannot be shared across them and no conflicts are going to happen.

此外,可以使用动态 T-SQL 语句为存储过程中的临时表命名不同的名称.例如,您可以使用序列来获取此类数字并将其连接到表名.但是,如果你这样做,你需要使用 sp_executesql 来创建你的表并用它做一些事情.这样,其他存储过程将无法读取/修改您在当前存储过程中创建的表.换句话说,如果使用动态 T-SQL 语句创建临时表,则无法通过例程共享该临时表.所以,做这种事绝对没有意义.

Also, naming a temporary table in stored procedure with different name can be done using a dynamic T-SQL statement. You can for example, use a sequence to get such number and concatenate it to the table name. But, if you do so, you need to use sp_executesql to create your table and do things with it. In such way, no other stored procedure would be able to read/modify the table you have created in the current stored procedure. In other words, the temporary table cannot be shared over the routines if created using dynamic T-SQL statement. So, there is absolutely no point of doing such thing.