嵌套Select Case的语法错误

时间:2017-09-02 14:16:21

标签: sql sql-server

任何人都可以请更正我的嵌套Select Case When的语法。

Update T
set P= a.Quantity
from
(
    select 
    case when D.P> T.Open
    then D.P

    from DOP D 
    inner join T
    on 
    D.PON = T.PON
)a

我是sql server的新手,所以不确定如何编写正确的选择案例。

2 个答案:

答案 0 :(得分:1)

CASE语句就像C#这样的语言中的switch语句。基本上它是一个复合结构,可以排成一堆if/else个东西。正如其中一条评论中所提到的,通常采用case when <first condition> then <result on first condition> when <nth condition> then <result of nth condition> <optional else clause> end的形式。请注意可选的else子句。如果省略,则任何不符合其中一个条件的值都将设置为null。

从你的例子来看,我不太清楚你想要在这里得到什么;您已经布局的两个路径最终都映射到D.POQty,并且case语句实际上只有在映射到不同的值时才有用。如果你想要的只是null行为,那就这样吧。但是你可能不需要案例陈述,或者至少不需要这种复杂性。

那就是说,为了展示你如何重构你的代码以使语句运行,这就是我想出的。我删除了子查询,因为您可以直接从case语句更新列。我还结合了你所拥有的复合案例陈述,因为我没有看到它添加了什么只是AND这两个条件不会。如果我没有得到您的要求,请告诉我。

update t2s -- References which aliased table you intend to update
set POQty = case when D.POQty > [Tab-2 sourcing].OpenQuantity 
                 then D.POQty 
                 when D.POQty < [Tab-2 sourcing].OpenQuantity and D.POQty > [Tab-2 sourcing].AlreadyAlloted
                 then D.POQty
                 else null -- This is implied if you leave it off. Just adding it in so that its behavior is clear
            end
from DemandPortal D 
inner join [Tab-2 sourcing] t2s
    on D.PONumber = t2s.PONumber

CASE声明文档:https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql

答案 1 :(得分:1)

我认为案件陈述没有必要。您可以在where子句中执行所有检查:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.atchaca.proverbialwisdom">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="com.android.vending.BILLING"/>


<application
    android:allowBackup="true"
    android:icon="@drawable/proverbial_wisdom_logo"
    android:label="@string/app_name"
    android:roundIcon="@drawable/proverbial_wisdom_logo_round"
    android:supportsRtl="true"
    android:theme="@style/FullyTheme">

    <activity android:name=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity 
        android:name=".MainActivity">
    </activity>

    <activity 
        android:name=".SnippetActivity">
    </activity>

    <activity 
        android:name=".AboutActivity">
    </activity>

    <activity 
        android:name=".FavouritesActivity">
    </activity>

    <activity 
        android:name=".TransactionsActivity">
    </activity>

    <activity 
        android:name=".FeedbackActivity">
    </activity>

    <activity 
        android:name=".DeveloperActivity">
    </activity>

</application>
相关问题