将逗号分隔的字符串转换为多个 ‘in’ 子句的值

huangapple go评论43阅读模式
英文:

Cast comma-separated string to multiple 'in' clause values

问题

将上面的SQL语句更改如下,以删除mytable中的三条记录:

SET @ids = '1,2,3';
SET @sql = CONCAT('DELETE FROM mytable WHERE id IN (', @ids, ')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

这将通过动态构建SQL语句来解决错误,并且能够从mytable中删除id为1、2和3的记录。

英文:
set @ids = '1,2,3';
delete from mytable where id in (@ids);

The sql statement above gives this error:

> Truncated incorrect DOUBLE value: '1,2,3'

How can I cast @ids, or write the query in another way, so that it deletes the three records from mytable?

Sql mode is set to
"IGNORE_SPACE,STRICT_TRANS_TABLES"

答案1

得分: 0

In end I went with a prepared statement.

set @ids = '1,2,3';
set @query = concat('delete from mytable where id in (',@ids,');');
PREPARE sql_query from @query;
EXECUTE sql_query;

英文:

In end I went with a prepared statement.

set @ids = '1,2,3';
set @query = concat('delete from mytable where id in (',@ids,');');
PREPARE sql_query from @query;
EXECUTE sql_query;

huangapple
  • 本文由 发表于 2023年5月17日 13:03:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定