Home > Database > Mysql Tutorial > sql server用变量动态命名临时表表名

sql server用变量动态命名临时表表名

WBOY
Release: 2016-06-07 15:07:37
Original
2214 people have browsed it

sql server不支持 动态 命名 局部 临时 表的表名,如以下语句并不能创建局部 临时 表: declare @n nvarchar(10),@s nvarchar(100) set @n = 'temp' set @s = N'select * into #'+@n+' from mytable' --print @s exec sp_executesql @s 以上语句并不提示错误

sql server不支持动态命名局部临时表的表名,如以下语句并不能创建局部临时表:
declare @n nvarchar(10),@s nvarchar(100)
set @n = 'temp'
set @s = N'select * into #'+@n+' from mytable'
--print @s
exec sp_executesql @s
以上语句并不提示错误,但查询#temp表时,提示#temp对象名无效。

如果需要动态创建表名,只能用以下两种方法:
1、创建全局临时表(用两个#)。
declare @n nvarchar(10),@s nvarchar(100)
set @n = 'temp'
set @s = N'select * into ##'+@n+' from mytable'
--print @s
exec sp_executesql @s
2、创建真正的表(去掉#),一定要小心的创建,小心的删除。
declare @n nvarchar(10),@s nvarchar(100)
set @n = 'temp'
set @s = N'select * into '+@n+' from mytable'
--print @s
exec sp_executesql @s
这种方法创建的表,存放在当前的数据库里,而不是像临时表一样存放在tempdb数据库里。 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template