无法创建同名但条件不同的临时表

uajslkp6  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(312)

如果cnt=1,那么我想创建一个包含2列的临时表;如果cnt=2,那么我想创建一个包含3列但名称相同的临时表,如下所示。

Declare @cnt int
Set @cnt = 2

IF @cnt = 1
Begin
if OBJECT_ID('tempdb..#temptest') is not null drop table #temptest;
create table #temptest
(   ID int,
    M1 char(2)
);
end

IF @cnt = 2
begin

if OBJECT_ID('tempdb..#temptest') is not null drop table #temptest;
create table #temptest
(   ID int,
    M1 char(2),
    M2 char(2)
);
end

我出错了
'数据库中已存在名为'#tentest'的对象。
怎么做。。请帮忙?

frebpwbc

frebpwbc1#

最简单的解决方案是创建包含所需最少列的temp表,然后根据@cnt的值根据需要添加列。试试这个:

DECLARE @cnt int
SET @cnt = 2

IF OBJECT_ID('tempdb..#temptest') is not null DROP TABLE #temptest;
CREATE TABLE #temptest
(   ID int,
    M1 char(2)
);

IF @cnt = 2
BEGIN

ALTER TABLE #temptest
ADD M2 char(2)

END

相关问题