我试图运行类似于以下内容的查询。我基本上试图有条件地更改更新文本的格式。我需要一些帮助,因为我已经尝试了几种不同的方法而没有成功。提前谢谢。
UPDATE bL SET
bL.[QUANTITY] = bL.[QUANTITY] + 2,
bL.[SERIAL_NUMBERS] =
(
CASE WHEN bL.[SERIAL_NUMBERS] IS NOT NULL
THEN ISNULL(bL.[SERIAL_NUMBERS], '') + 'EOSB7U310007; EOSB7U310022'
ELSE bL.[SERIAL_NUMBERS] + '; EOSB7U310007; EOSB7U310022'
)
FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES_LINES] AS bL
LEFT JOIN [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES] AS bO
ON bL.[AOF_BOXES_ID] = bO.[ID]
WHERE bO.[SELECTED] = 'True'
答案 0 :(得分:2)
因此,将我发现的所有评论放在一个答案中,您的代码应该如下所示:
UPDATE bL SET
bL.[QUANTITY] = bL.[QUANTITY] + 2,
bL.[SERIAL_NUMBERS] =
(
CASE WHEN bL.[SERIAL_NUMBERS] IS NULL
THEN 'EOSB7U310007; EOSB7U310022'
ELSE bL.[SERIAL_NUMBERS] + '; EOSB7U310007; EOSB7U310022'
END
)
FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES_LINES] AS bL
LEFT JOIN [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES] AS bO
ON bL.[AOF_BOXES_ID] = bO.[ID]
AND bO.[SELECTED] = 'True'
然而它可以缩短 - 像这样:
UPDATE bL SET
bL.[QUANTITY] = bL.[QUANTITY] + 2,
bL.[SERIAL_NUMBERS] = ISNULL(bL.[SERIAL_NUMBERS] + '; ', '') + 'EOSB7U310007; EOSB7U310022'
FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES_LINES] AS bL
LEFT JOIN [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES] AS bO
ON bL.[AOF_BOXES_ID] = bO.[ID]
AND bO.[SELECTED] = 'True'
这是因为它bL.[SERIAL_NUMBERS]
的值为null,那么它与;
的串联也将为空。
注意:
我已将bO.[SELECTED] = 'True'
从WHERE
子句移至ON
子句。这是因为当使用左连接时,右表上的所有条件都应该在ON
子句上,否则连接将变为内连接。
好像您正在使用bL.[SERIAL_NUMBERS]
列来存储多个值。这是99.9999%的案件中的一个大错误
阅读Is storing a delimited list in a database column really that bad?,您将看到很多原因。
答案 1 :(得分:1)
您不需要SELECT
,而且必须END
发出CASE
声明。
UPDATE bL
SET bL.[QUANTITY] = bL.[QUANTITY] + 2
, bL.[SERIAL_NUMBERS] = ( CASE WHEN bL.[SERIAL_NUMBERS] IS NOT NULL
THEN ISNULL(bL.[SERIAL_NUMBERS] , '') + 'EOSB7U310007; EOSB7U310022'
ELSE bL.[SERIAL_NUMBERS] + '; EOSB7U310007; EOSB7U310022'
END )
FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES_LINES] AS bL
LEFT JOIN [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES] AS bO ON bL.[AOF_BOXES_ID] = bO.[ID]
WHERE bO.[SELECTED] = 'True';