1

我想使用WITH子句更新我的表。我在尝试:

UPDATE mytable 
SET myfield = (
   WITH sub AS (SELECT 18) 
   SELECT CASE WHEN (sub = 18) THEN 100 ELSE 0 END)

WITH sub AS (SELECT 18)
UPDATE mytable 
SET myfield = ( 
   SELECT CASE WHEN (sub = 18) THEN 100 ELSE 0 END)

但它不起作用。请向我解释我做错了什么。

4

3 回答 3

1

sub是记录集,而不是列。这将起作用:

with sub(col) as (select 18)
update mytable set
   myfield = (select case when col = 18 then 100 else 0 end from sub)

但它会mytable用 100 更新所有行。不知道你想对查询做什么,所以不能更精确。

于 2013-11-05T17:12:52.517 回答
0
UPDATE mytable 
SET myfield = (
   WITH sub AS (SELECT 18 AS field) 
   SELECT CASE WHEN (field = 18) THEN 100 ELSE 0 END
   FROM sub)
于 2013-11-05T16:46:14.070 回答
0

WITH 子句定义了“公用表表达式”,在后续查询中被视为表。因此,您仍然需要像引用表一样在后续查询中引用公用表表达式名称,并且我发现在 CTE 名称前加上 cte_ 前缀更清楚,只是为了在复杂表达式中清楚地说明数据是。

update mytable 
set    myfield = (
         with cte_sub as
           (select 18 as field) 
         select case field
                  when 18 then 100
                  else 0
                end
         from cte_sub)
于 2013-11-05T17:08:31.037 回答