2011年3月7日 星期一

if .. else .. create table variable

想要動依不同情況建立相同名稱的table variable,語法如下
 if @condition = '1'
begin
  declare @tmptable1 table (col1 int,col2 int)
end
else
begin
  declare @tmptable1 table (col1 int,col2 int, col3 int, col4 int)
end

出現以下錯誤
Msg 134, Level 15, State 1, Line 13
The variable name '@tmptable1' has already been declared. Variable names must be unique within a query batch or stored procedure.

改成用temp table 也不行
 if @condition = '1'
begin
    create table #tmptable1  (col1 int,col2 int)
end
else
begin
   create table #tmptable1  (col1 int,col2 int, col3 int, col4 int)
end


 出現以下錯誤
Msg 2714, Level 16, State 1, Line 15
There is already an object named '#tmptable1' in the database.

最後折衷好了...馬是口以啦...

 create table #tmptable1  (col1 int,col2 int, col3 int, col4 int)
 if @condition = '1'
begin
    alter table #tmptable1
    drop column col3,col4
end

 

沒有留言:

張貼留言

離線安裝SSMS 22 launched extracted application exiting with result code 0x138b

SSMS 22 安裝器下載頁面 https://learn.microsoft.com/zh-tw/ssms/install/install https://aka.ms/ssms/22/release/vs_SSMS.exe 將安裝檔下載到本機,檔案好大2.5G  https:...