SQL-基于特定对象属性替换值
我正在尝试在SQL中编写有条件的更新语句,该语句查看一系列对象,并根据另一个对象的属性更新一个对象属性。以下是我要更新的signal_key
列中对象的示例。
{
"entities": [
{"type": "MERCHANT", "value": "AAAA"},
{"type": "MERCHANT", "value": "CCC"}],
"signalType": "TRANSACTION",
"signalVersion": "0"
}
基于“ value”字符串,我想将“类型”从商家
更新为id
。我有没有办法专门检查值,而不是使用像之类的东西,它会在整个对象中寻找字符串比较?下面,signal_key ???
指示我要问的查询的部分。
UPDATE signals
SET signal_key??? = CASE
WHEN signal_key??? = 'AAAA' THEN 'BBBB'
WHEN signal_key??? = 'CCC' THEN 'DDD'
ELSE signal_key???
END
WHERE signal_key??? IN ('AAAA', 'CCC')
I'm trying to write a conditional update statement in SQL that looks at an array of objects, and updates one object property based on another object's property. Below is an example of an object in the signal_key
column that I'm trying to update.
{
"entities": [
{"type": "MERCHANT", "value": "AAAA"},
{"type": "MERCHANT", "value": "CCC"}],
"signalType": "TRANSACTION",
"signalVersion": "0"
}
Based on the "value" string, I want to update the "type" from MERCHANT
to ID
. Is there a way for me to specifically check value instead of using something like LIKE
that would look for a string comparison in the whole object? Below, signal_key???
indicates the portion of the query that I am asking about.
UPDATE signals
SET signal_key??? = CASE
WHEN signal_key??? = 'AAAA' THEN 'BBBB'
WHEN signal_key??? = 'CCC' THEN 'DDD'
ELSE signal_key???
END
WHERE signal_key??? IN ('AAAA', 'CCC')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
len(my_field)
检查长度:
编辑:基于相关数据更新:
首先创建一个CTE(常见表达式,使用
带有
),其中包含每个项目,其中包含相关项目的长度。在下面的示例中,CTE包含每个项目ID,其中包含相关项目的计数(或“长度”)。然后发出更新语句,该语句使用与要更新的表连接的长度表。
You can use
Len(my_field)
to check the lengthFor example:
Edit: To update based on related data:
First create a CTE (common table expression, using
with
) that contains each item with the length of the associated items. In the example below the CTE contains each item id with the count (or "length") of associated items.Then issue an update statement that uses the length table joined with the table you want to update.
要解析JSON,您应该使用SQL Server的JSON功能。
您需要在相关的子查询中使用
OpenJson
以找到正确的修改索引。如果您只想修改每行单个值,则可以这样做。
否则您需要重建JSON阵列
To parse JSON, you should use SQL Server's JSON capabilities.
You need to use
OPENJSON
in a correlated subquery to find the right index to modify.If you only want to modify a single value per row, you can do it like this.
Otherwise you need to rebuild the JSON array