今天遇到一个需求,是根据逻辑判断动态创建局部临时表
1
declare
@flag
bit
2
3
select
@flag
=
1
4
5
--
当@flag=1时,临时表第2个字段a的类型为float
6
7
--
当@flag<>1时,临时表第2个字段a的类型为int
8
9
if
@flag
=
1
10
11
begin
12
13
create
table
#TemTable(ids
int
, a
float
)
14
15
end
16
17
else
18
19
begin
20
21
create
table
#TemTable(ids
int
,a
int
)
22
23
end
24
25

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

运行时出现错误提示如下:
服务器: 消息 2714,级别 16,状态 1,行 9
数据库中已存在名为 '#TemTable' 的对象。
看来创建临时表也和声明变量一样
想来想去,考虑了解决方式有2种:
1.命名2个不同的表名称
#TemTable1和#TemTable2
2.先创建表的基本结构,再根据条件修改表结构
1
declare
@flag
bit
2
3
select
@flag
=
1
4
5
create
table
#TemTable(ids
int
)
6
7
if
@flag
=
1
8
9
begin
10
11
alter
table
#TemTable
12
13
add
a
float
14
15
end
16
17
else
18
19
begin
20
21
alter
table
#TemTable
22
23
add
a
int
24
25
end
26
27
go
28
29
--
表结构改变后要重新编译
30
31
select
*
from
#TemTable
32
33
insert
into
#TemTable
34
35
select
1
,
1
36
37
drop
table
#TemTable
38

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

请注意表变量也会有这样的问题
希望上面提到的知识对你有所提示
当然欢迎交流和指正
blog:
http://www.cnblogs.com/aierong
author:aierong
email:aierong@126.com