我希望能够根据输入参数的值选择我的存储过程更新表中的哪个字段。如果输入字段等于“草稿”,则应更新 id_draft ,否则应更新 id 。 这可能吗?
这是我失败的尝试之一,可能有助于说明我想要做的事情:
CREATE OR REPLACE PROCEDURE sp_test (input_field VARCHAR DEFAULT NULL)
IS
BEGIN
UPDATE TABLE
SET
CASE
WHEN input_field = 'draft' THEN id_draft
ELSE id
END = 'x'
答案 0 :(得分:2)
您不能使用CASE语句来更改查询结构本身。它只返回数据,它是一个函数。
您拥有的内容(CASE WHEN input_field = 'draft' then id_draft ELSE id END
)会在id
字段或id_draft
字段中返回 值 。这就像这样......
UPDATE
yourTable
SET
CASE WHEN 'abc' = 'draft' THEN 123 ELSE 789 END = 'x'
相反,您需要将CASE语句放在右侧......
UPDATE
yourTable
SET
id = CASE WHEN input_field = 'draft' THEN id ELSE 'x' END,
id_draft = CASE WHEN input_field = 'draft' THEN 'x' ELSE id_draft END
但实际上,你可能会做得更好......
IF (input_field = 'draft')
UPDATE yourTable SET id_draft = 'x'
ELSE
UPDATE yourTable SET id = 'x'
修改:* 强>
要使用其他表格中的值而不只是'x'
,您可以使用类似的内容......
UPDATE
yourTable
SET
id = CASE WHEN input_field = 'draft' THEN yourTable.id ELSE otherTable.x END,
id_draft = CASE WHEN input_field = 'draft' THEN otherTable.x ELSE yourTable.id_draft END
FROM
otherTable
WHERE
otherTable.a=? AND otherTable.b=?