Search code examples
sqlwhere-clausesql-likesql-in

VB.Net SQL Query - I am trying to Concatenate two columns however I am running into issues


Below is a query I am trying to execute. I get an error

ClassItem is not a column name.

Please can somebody let me know where I am going wrong in this query.

SELECT 
    *, CONCAT([Cabin], [Item]) AS ClassItem 
FROM 
    FQR_RAW_1 AS ClassItem 
WHERE 
    ClassItem IN ('%JCHML - Child Meal%', '%WCHML - Child Meal%', '%YMC - Beef%', '%YMC - Chicken%', '%YMC - Fish / Shellfish%', '%YMC - Pork%', '%YMC - Regional Taste (Non Veg)%', '%YMC - Regional Taste (Veg)%', '%YMC - Vegetarian%')  
    AND [Origin Region] LIKE 'USA%'

Solution

  • You can't reuse a column defined in the select clause in the where clause - here, that's ClassItem.

    Another problem is that you cannot use IN with wildcard %, which seems to be your intent here. You might be looking for a series of OR condition instead:

    SELECT *, CONCAT([Cabin], [Item]) as ClassItem 
    FROM FQR_RAW_1  
    WHERE 
        (
               CONCAT([Cabin], [Item]) LIKE '%JCHML - Child Meal%'
            OR CONCAT([Cabin], [Item]) LIKE '%WCHML - Child Meal%'
            OR CONCAT([Cabin], [Item]) LIKE '%YMC - Beef%'
            OR CONCAT([Cabin], [Item]) LIKE '%YMC - Chicken%'
            OR CONCAT([Cabin], [Item]) LIKE '%YMC - Fish / Shellfish%'
            OR CONCAT([Cabin], [Item]) LIKE '%YMC - Pork%', 
            OR CONCAT([Cabin], [Item]) LIKE '%YMC - Regional Taste (Non Veg)%'
            OR CONCAT([Cabin], [Item]) LIKE '%YMC - Regional Taste (Veg)%'
            OR CONCAT([Cabin], [Item]) LIKE '%YMC - Vegetarian%'
        ) 
        AND [Origin Region] LIKE 'USA%'
    

    Note that I also removed the table alias, that is actually not needed in the query, and that was identical to the column alias - although SQL supports that, this is a bit confusing. If you need to alias the table for some reason, then use another alias.