我試圖創建一個MySQL片段,將分析表,並刪除重複項(副本是基於兩個字段而不是整個記錄)MYSQL變量 - SET @var
我有以下的代碼,我的作品時,硬編碼在查詢中的變量,但是當我帶他們出去,並把它們作爲變量,我得到的MySQL錯誤,下面是腳本:
SET @tblname = 'mytable';
SET @fieldname = 'myfield';
SET @concat1 = 'checkfield1';
SET @concat2 = 'checkfield2';
ALTER TABLE @tblname ADD `tmpcheck` VARCHAR(255) NOT NULL;
UPDATE @tblname SET `tmpcheck` = CONCAT(@concat1,'-',@concat2);
CREATE TEMPORARY TABLE `tmp_table` (
`tmpfield` VARCHAR(100) NOT NULL
) ENGINE = MYISAM ;
INSERT INTO `tmp_table` (`tmpfield`) SELECT @fieldname FROM @tblname GROUP BY `tmpcheck` HAVING (COUNT(`tmpcheck`) > 1);
DELETE FROM @tblname WHERE @fieldname IN (SELECT `tmpfield` FROM `tmp_table`);
ALTER TABLE @tblname DROP `tmpcheck`;
我收到以下錯誤:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@tblname ADD `tmpcheck` VARCHAR(255) NOT NULL' at line 1
這是因爲我無法使用變量作爲表名?還有什麼可能是錯的,或者我將如何解決這個問題。
現在我已經試過PREPARE stmt_name FROM; 「ALTER TABLE ADD'tmpcheck' VARCHAR(255)NOT NULL?」 SET @tblname ='mytable'; EXECUTE stmt_name USING @tblname; DEALLOCATE PREPARE stmt_name; 但在'?'處發生錯誤 – Lizard 2010-05-13 12:06:15
關於不能爲表名使用變量的相同規則可能適用於語句參數。用CONCAT()連接表名,而不是將其作爲參數。 – 2010-05-13 12:08:39