Skip to content
Advertisement

SQL Server : concatenate and where clause

I am trying to concatenate three columns from two tables Customer and Invoice, create a new column and find the new_id member whose name begins from ‘Astridgruber’ in SQl Server.

The below is causing an error.

select 
    concat(c.FirstName, c.LastName, i.InvoiceId) as New_Id
from 
    Invoice i, Customer c
where 
    i.[CustomerId] = c.CustomerId 
where 
    New_Id = 'AstriGruber%'

Help will be much appreciated.

These are the tables from the Chinook Database:

image

Advertisement

Answer

Too long for a comment. You have a few issues:

  1. You should be using modern, explicit JOIN syntax, not comma joins;
  2. Too many WHERE clauses; AND the conditions together;
  3. You can’t use aliases in WHERE clauses; replace New_Id with concat(c.FirstName,c.LastName,i.InvoiceId);
  4. You should be using LIKE, not =

All up your query should look like:

select concat(c.FirstName,c.LastName,i.InvoiceId) as New_Id
from Invoice i
join Customer c on i.CustomerId = c.CustomerId 
where concat(c.FirstName,c.LastName,i.InvoiceId) LIKE 'AstriGruber%'

Demo on dbfiddle

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement