日期:2014-05-18  浏览次数:20463 次

存储过程中临时表的问题
我想在存储过程中生成临时表,然后再从临时表中使用计算什么的
可是EXEC   sp_executesql   @sql   后临时表就不存了
使用全局临时表的话,多人同时操作该存储过程又有问题
要如何解决呢?谢谢

------解决方案--------------------
临时表的作用域即是如此


先建立临时表.
再 exec sp_executesql
这样就可以引用了.


如果只能在 exec sp_executesql中建立临时表, 那么引用也只能够在这里面
------解决方案--------------------
搬個板凳來學習~~~~
------解决方案--------------------
在EXEC sp_executesql @sql 中创建与引用临时表!
------解决方案--------------------
参考:
关于sql server中临时表的概念理解,扬帆破浪,openvms
A :




The two types of temporary tables, local and global, differ from each other in their names, their visibility, and their availability. Local temporary tables have a single number sign (#) as the first character of their names; they are visible only to the current connection for the user; and they are deleted when the user disconnects from instances of Microsoft® SQL Server™ 2000. Global temporary tables have two number signs (##) as the first characters of their names; they are visible to any user after they are created; and they are deleted when all users referencing the table disconnect from SQL Server.



For example, if you create a table named employees, the table can be used by any person who has the security permissions in the database to use it, until the table is deleted. If you create a local temporary table named #employees, you are the only person who can work with the table, and it is deleted when you disconnect. If you create a global temporary table named ##employees, any user in the database can work with this table. If no other user works with this table after you create it, the table is deleted when you disconnect. If another user works with the table after you create it, SQL Server deletes it when both of you disconnect.

上面是拷贝自sql server2000的book online

主要是为了这样一个问题,在我的模块中的一个存储过程中,我创建并使用了一个临时表#myTempTable.如果多个人(未知多少)使用一个login登陆到数据库操纵这个模块。会不会发生并发?

上面的E文描述,local的临时表是针对于current connection的。是不是并发问题sql server已经帮我们搞定了?

---------------------------



是的,不会有并发问题,local temporary table(#myTempTable)按连接命名,在数据库的名称是形如#myTempTable___________12345的,不同连接的临时表的名的后面部分是不一样的,这个你可以在TEMPDB的SYSOBJECTS表查到。



---------------------------



临时表

可以创建本地和全局临时表。本地临时表仅在当前会话中可见;全局临时表在所有会话中都可见。



本地临时表的名称前面有一个编号符 (#table_name),而全局临时表的名称前面有两个编号符 (##table_name)。



SQL 语句使用 CREATE TABLE 语句中为 table_name 指定的名称引用临时表:



CREATE TABLE #MyTempTable (cola INT PRIMARY KEY)

INSERT INTO #MyTempTable VALUES (1)



如果本地临时表由存储过程创建或由多个用户同时执行的应用程序创建,则 SQL Server 必须能够区分由不同用户创建的表。为此,SQL Server 在内部为每个本地临时表的表名追加一个数字后缀。存储在 tempdb 数据库的 sysobjects 表中的临时表,其全名由 CREATE TABLE 语句中指定的表名和系统生成的数字后缀组成。为了允许追加后缀,为本地临时表指定的表名 table_name 不能超过 116 个字符。



除非使用 DROP TABLE 语句显式除去临时表,否则临时表将在退出其作用域时由系统自动除去:



当存储过程完成时,将自动除去在存储过程中创建的本地临时表。由创建表的存储过程执行的所有嵌套存储过程都可以引用此表。但调用创建此表的存储过程的进程无法引用此表。





所有其它本地临时表在当前会话结束时自动除去。





全局临时表在创建此表的会话结束且其它任务停止对其引用时自动除去。任务与表之间的关联只在单个 Transact-SQL 语句的生存周期内保持。换言之,当创建全局临时表的会话结束时,最后一条引用此表的 Transact-SQL 语句完成后,将