无法创建名称相同但条件不同的临时文件 table

Unable to create temp table with same name but in different condition

if cnt=1 然后我想创建一个有 2 列的临时 table 当 cnt = 2 时我想要一个有 3 列的临时 table 但名称如下。

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

遇到错误

'There is already an object named '#temptest' in the database.

怎么做..请帮忙?

最简单的解决方案是使用所需的最少列创建临时 table,然后根据 @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