2013-09-03

stored procedure IF ELSE SELECT INTO 出現 [訊息2714 層級16] 錯誤訊息

--範例
--建立暫存表
IF UPPER(@ServerNa) = 'SERVAER_A'
BEGIN
 IF (SELECT OBJECT_ID('tempdb..#STUL')) IS NOT NULL DROP TABLE #STUL
 select DISTINCT CorpNo,IONo into #STUL
 from [SERVAER_A].InnovaERP.dbo.SysTableUpdateLog
 where PrgType=@PrgType
END
ELSE IF UPPER(@ServerNa) = 'SERVAER_B'
BEGIN
 IF (SELECT OBJECT_ID('tempdb..#STUL')) IS NOT NULL DROP TABLE #STUL
 select DISTINCT CorpNo,IONo into #STUL
 from [SERVAER_B].InnovaERP.dbo.SysTableUpdateLog
 where PrgType=@PrgType
END
--錯誤訊息
訊息 2714,層級 16,狀態 1,程序 SP_XXX,行 24
資料庫中已經有一個名為 '#STUL' 的物件。
通常在不同的IF ELSE判斷子句中,應該可以視為獨立的事件,
不知為什麼MS SQL在stored procedure中,
使用IF ELSE針對不同的條件SELECT INTO到同樣的表格,會有這樣的錯誤訊息,
只好改寫語法,於判斷式前先將暫存表建立,再於子句中INSERT INTO即可

--建立暫存表
IF (SELECT OBJECT_ID('tempdb..#STUL')) IS NOT NULL DROP TABLE #STUL
SELECT TOP 1 CorpNo,IONo
  INTO #STUL
FROM SysTableUpdateLog

IF UPPER(@ServerNa) = 'SERVAER_A'
BEGIN
 INSERT INTO #STUL
 select DISTINCT CorpNo,IONo
 from [SERVAER_A].InnovaERP.dbo.SysTableUpdateLog
 where PrgType=@PrgType
END
ELSE IF UPPER(@ServerNa) = 'SERVAER_B'
BEGIN
 INSERT INTO #STUL 
 select DISTINCT CorpNo,IONo
 from [SERVAER_B].InnovaERP.dbo.SysTableUpdateLog
 where PrgType=@PrgType
END

沒有留言: