2014-02-25 63 views
0

看看這段代碼。它應該告訴你什麼是我想要做的事:是否可以使用MySQL動態創建存儲過程中的表名稱?

SELECT type from barcodes where barcode = barcodeApp INTO @barcodeType; 
IF (@barcodeType = 'videogame') THEN 
    SET @barcodeType = 'game'; 
END IF; 

DELETE FROM @barcodeType + itemdetails_custom 
WHERE barcode = barcodeApp 
AND username = usernameApp; 

正如你所看到的,在DELETE FROM的一部分,我想動態地放在一起從以前的查詢結果表名。這可能嗎?

另外,如果您發現上述問題,請告訴我。我絕對不是MySQL專家。

+0

什麼是'barcodeApp'和'usernameApp'?變量或列名稱? –

+0

是的,從用戶發送到sproc的變量 –

回答

1

您需要使用Prepared Statement來執行動態準備的查詢。

嘗試下面的代碼:

set @del_query = concat('DELETE FROM ', @finalType) 
set @del_query = concat('\'', itemdetails_custom, '\''); 
set @del_query = concat(@del_query, ' WHERE barcode = \'', barcodeApp, '\''); 
set @del_query = concat(@del_query, ' AND username = \'', usernameApp, '\''); 

prepare stmt from @del_query; 
execute stmt; 
drop prepare stmt; -- deallocate prepare stmt; 

:我認爲barcodeAppusernameApp是變量。否則,請在上面的查詢中移除它們周圍的單引號。

+0

Works!儘管你忘記了itemdetails_custom的單引號。 :) –

相關問題