【问题标题】:How to cast string input into "where in"如何将字符串输入转换为“在哪里”
【发布时间】:2021-03-01 20:13:57
【问题描述】:
我的数据库事物中有一个 Thingworx 服务(SQL 查询),例如。 GetCookiesByIds
我有一个参数ids (STRING),其值为1,2,3
我想查询:
SELECT * FROM Cookies WHERE id IN ([[ids]])`
但我有一个例外。
如何将我的参数 ID 转换为有效格式?
【问题讨论】:
标签:
sql
string
postgresql
csv
thingworx
【解决方案1】:
一个简单的便携选项是:
select *
from cookies
where ',' || $1 || ',' like '%,' || id || ',%'
... 其中$1 表示作为查询参数的 CSV 字符串。
在 Postgres 中,我们也可以使用数组:
select *
from cookies
where id = any(string_to_array($1, ','))
【解决方案2】:
一)
SELECT * FROM cookies WHERE id = any([[ids]]::int[])
ids 的值必须是:{1,2,3}
B)
SELECT * FROM cookies WHERE id = any(
CONCAT( '{', [[ids]], '}' ) ::int[]
)
ids 的值必须是:1,2,3
【解决方案3】:
如果你想这样做,语法是这样的
SELECT * FROM Cookies WHERE id IN (<<ids>>)
如果您使用<<>>,Thingworx 服务将在查询中连接您的输入参数,如果您使用[[]],则将其定义为实际参数