虽然我指定一个表达式sql给出"只能指定一个表达式错误"

时间:2017-02-13 00:37:46

标签: sql-server tsql

    DS.SOURCE_TYPE,
    (SELECT  
         I_MAX_VADE,
         CASE 
            WHEN (PA.ACTOR_KIND = 5 AND PA.PROCESS_ID = PROCESS_ID) 
               THEN 0 
               ELSE I_MAX_VADE 
         END   
     FROM 
         KDS_INTER_FAKTORING_OMDM_PARAMS 
     WHERE 
         PA.ID = PROCESS_ACTOR_ID) AS TERER
FROM             
    dbo.PROCESS_ACTOR AS PA  
JOIN
    dbo.OMDM_RESULT AS O ON O.PROCESS_ID = PA.PROCESS_ID
JOIN 
    dbo.KDS_PROPOSAL_OMDM_PARAMS AS POP ON POP.PROCESS_ID = PA.PROCESS_ID
JOIN 
    dbo.PROPOSAL_SNAP AS PS ON PS.PROCESS_ID = PA.PROCESS_ID
JOIN 
    dbo.DEBTOR_SNAP AS DS ON DS.PROCESS_ID = PA.PROCESS_ID

这个简单的查询会抛出下面指定的错误。

我想我已经在子查询中选择了一列。我想将I_MAX_VADE分配给它的db值。

if (PA.ACTOR_KIND = 5 AND PA.PROCESS_ID = PROCESS_ID) else zero.

当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。

4 个答案:

答案 0 :(得分:2)

您的子查询select会返回两列:I_MAX_VADECASE表达式的结果。这太多了。

答案 1 :(得分:2)

使用OUTER APPLY。它就像一个相关的子查询(有时),但它在FROM子句而不是SELECT。并且,您可以拥有任意数量的列:

SELECT . . .,
       DS.SOURCE_TYPE,
       params.*
FROM dbo.PROCESS_ACTOR PA  JOIN
     dbo.OMDM_RESULT O
     ON O.PROCESS_ID = PA.PROCESS_ID JOIN
     dbo.KDS_PROPOSAL_OMDM_PARAMS POP
     ON POP.PROCESS_ID = PA.PROCESS_ID JOIN
     dbo.PROPOSAL_SNAP PS
     ON PS.PROCESS_ID = PA.PROCESS_ID JOIN
     dbo.DEBTOR_SNAP DS
     ON DS.PROCESS_ID = PA.PROCESS_ID OUTER APPLY
     (SELECT I_MAX_VADE,
             (CASE WHEN PA.ACTOR_KIND = 5 AND PA.PROCESS_ID = params.PROCESS_ID THEN 0 
                   ELSE params.I_MAX_VADE
              END) as TERER 
       FROM KDS_INTER_FAKTORING_OMDM_PARAMS params
       WHERE PA.ID = params.PROCESS_ACTOR_ID
     ) params

注意:我不得不猜测几列的来源。您应始终限定列名称 - 当您使用相关子查询时,这一点更为重要。

答案 2 :(得分:1)

+1从HABO回答,但我会添加一个例子:

<强> WRONG:

SELECT A, B, (SELECT X, Y FROM MyTable) AS C
FROM OtherTable

将子查询放入选择列表时,子查询必须是标量子查询;即必须保证返回一列一行。

上面的示例是错误的,因为子查询返回两列,并且不一定会返回单行。

从右:

SELECT A, B, (SELECT TOP 1 X FROM MyTable) AS C
FROM OtherTable

答案 3 :(得分:0)

我终于明白了如何完成任务。这是我的更新代码。

我只是从select case中删除我的列(I_MAX_VADE)并将其插入then子句中。

**

之前

**

(SELECT  
         I_MAX_VADE,
         CASE 
            WHEN (PA.ACTOR_KIND = 5 AND PA.PROCESS_ID = PROCESS_ID) 
               THEN 0 
               ELSE I_MAX_VADE 
         END   
     FROM 
         KDS_INTER_FAKTORING_OMDM_PARAMS 
     WHERE 
         PA.ID = PROCESS_ACTOR_ID) AS TERER

**

**

(SELECT 
(CASE 
WHEN (PA.ACTOR_KIND=5) 
THEN (SELECT I_MAX_VADE FROM KDS_INTER_FAKTORING_OMDM_PARAMS 
WHERE PA.ID=PROCESS_ACTOR_ID )
ELSE 0 END) ) AS TERER