简体   繁体   中英

SQL Query Microsoft Azure Case Expression not working with new created column names/variables

I have created to new column names SKU and Materialnumber with a function. But when i create a case with these two columns the system does not recognize these two objects and i get a error message:

Msg 207, Level 16, State 1, Line 8
Invalid column name 'Materialnumber'.
Msg 207, Level 16, State 1, Line 8
Invalid column name 'SKU'

This is my code.

SELECT
     (Dokument +'.'+ Vs) as JBR_with_version,
     Beschreibung as Description_JBR,
     ObjKey,
     SKU=SUBSTRING(ObjKey,7,5)+'-'+SUBSTRING(ObjKey,12,5)+'-'+SUBSTRING(ObjKey,17,2),
     Materialnumber=SUBSTRING(Beschreibung,1,5)+'-'+SUBSTRING(Beschreibung,7,5)+ 
     '-'+SUBSTRING(Beschreibung,13,2),
        CASE
            WHEN Materialnumber != SKU AND Materialnumber like '[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9]' THEN Materialnumber
            ELSE 'n.a.'
            END AS Materialnumber
FROM
    dbo.SAP_JBR_SKU_Report
WHERE
     ObjKey like '[0-9]%' 

How can i define Materialnumber and SKU in a correct way to use the Case function?

You should use SELECT AS for these 'calculated` columns.

SELECT
     (Dokument +'.'+ Vs) as JBR_with_version,
     Beschreibung as Description_JBR,
     ObjKey,
     (SUBSTRING(ObjKey,7,5)+'-'+SUBSTRING(ObjKey,12,5)+'-'+SUBSTRING(ObjKey,17,2)) AS 'SKU',
     (SUBSTRING(Beschreibung,1,5)+'-'+SUBSTRING(Beschreibung,7,5)+ 
     '-'+SUBSTRING(Beschreibung,13,2)) AS 'Materialnumber',
        CASE
            WHEN Materialnumber != SKU AND Materialnumber like '[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9]' THEN Materialnumber
            ELSE 'n.a.'
            END AS Materialnumber
FROM
    dbo.SAP_JBR_SKU_Report
WHERE
     ObjKey like '[0-9]%' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM