这是我当前的SQL的样子:
DELIMITER $$ CREATE PROCEDURE updateDefaultUserRole( IN rid_in INT ) BEGIN ALTER TABLE _users MODIFY rid INT(255) NOT NULL DEFAULT rid_in; -- Modify the columns default value UPDATE _users SET rid = rid_in WHERE rid < rid_in; -- Update all entries lower than the role ID. END $$ DELIMITER ;
这是我的数据库_users表的样子:
CREATE TABLE `_users` ( `uid` int(255) NOT NULL, `forname` varchar(40) NOT NULL, `surname` varchar(40) NOT NULL, `email` varchar(120) NOT NULL, `hash` varchar(60) NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `rid` int(255) NOT NULL DEFAULT '2' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `_users` ADD PRIMARY KEY (`uid`), ADD KEY `rid` (`rid`); MODIFY `uid` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
我收到此错误:
您的SQL语法有误;检查与您的MariaDB服务器版本相对应的手册,以在’rid_in附近使用正确的语法;-修改列的默认值
链接到此行:
ALTER TABLE _users MODIFY rid INT(255) NOT NULL DEFAULT rid_in;
如果我更改此设置,则忽略该rid_in值:
rid_in
ALTER TABLE _users MODIFY rid INT(255) NOT NULL DEFAULT '1';
它工作正常,如何将rid_in输入绑定到查询?
我的预期输出是能够用来更改默认用户角色值并将具有旧用户值的所有行更新为新行:
CALL updateDefaultUserRole(@someInt)
为了能够更新每个用户的默认值。
您需要在此处使用动态SQL,因为Default中的as子句Alter Table将无法解析变量值:
Default
Alter Table
DELIMITER $$ CREATE PROCEDURE updateDefaultUserRole( IN rid_in INT ) BEGIN -- generate the query string for Alter Table SET @alter_query_str = CONCAT('ALTER TABLE _users MODIFY rid INT(255) NOT NULL DEFAULT ', rid_in); -- Modify the columns default value -- prepare the query PREPARE stmt FROM @alter_query_str; -- execute the query EXECUTE stmt; -- deallocate the query DEALLOCATE PREPARE stmt; UPDATE _users SET rid = rid_in WHERE rid < rid_in; -- Update all entries lower than the role ID. END $$ DELIMITER ;