sql - Oracle 根据输入参数更新字段 A 或字段 B

标签 sql oracle input parameters

我希望能够根据输入参数的值选择存储过程更新表中的哪个字段。如果输入字段等于“草稿”,则应更新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'

最佳答案

您不能使用 CASE 语句来更改查询结构本身。它只返回数据,它是一个函数。

您拥有的 ( CASE WHEN input_field = 'draft' then id_draft ELSE id END ) 返回 id 中的字段或id_draft field 。就像这样做...

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=?

关于sql - Oracle 根据输入参数更新字段 A 或字段 B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11448302/

相关文章:

sql - 如何从MySQL存储过程的多重选择中仅返回一个记录集?

sql - T-SQL 美元符号表达式

sql - Group By 子句导致错误

PHP 和 Oracle - oci_connect() ORA-12705 : Cannot access NLS data files

sql-server - Oracle 和 SQL Server 保留关键字

angularjs - 如何为 Angular js 应用程序添加 "datetime"选择器?

php - Codeigniter 更新查询不起作用

oracle - Liferay portlet 非liferay JNDI 数据源null

c++ - 用 cin 缓冲区做东西直到空

html - 制作一个接受表情符号的 1 个字符的 HTML 输入字段