SQL逗号语法错误求助:SELECT语句CAST函数附近报错
Hey there, let's sort out that syntax error you're running into! The root cause is a missing closing parenthesis in your concatenated job title expression.
Looking at your code, you opened a parenthesis for the concatenation (EmployeeTitles.Title + ' ' + CAST(Employees.Level AS VARCHAR) but never closed it before adding the comma for the next column (Employees.Salary). The database can't parse where that concatenation ends, so it throws an error right at the comma after the CAST statement.
Corrected Query
Here's the fixed version, with the missing parenthesis added. I also gave that concatenated title column a clear alias (JobTitle) to make your result set more readable:
SELECT Regions.RegionName, Countries.CountryName, (Employees.LastName + ', ' + Employees.FirstName) AS EmployeeName, (EmployeeTitles.Title + ' ' + CAST(Employees.Level AS VARCHAR)) AS JobTitle, Employees.Salary FROM Regions, Countries, Employees, EmployeeTitles WHERE Regions.RegionID = Countries.RegionID AND Countries.CountryID = Employees.CountryID AND Employees.TitleID = EmployeeTitles.TitleID ORDER BY RegionName, CountryName, LastName, Title, Salary;
Bonus: Boost Readability with Explicit JOINs
While we're at it, I’d recommend using explicit INNER JOIN syntax instead of the old comma-separated table list. It makes your join logic clearer and reduces the chance of accidental Cartesian products. Here's how that would look, with table aliases to keep the code concise:
SELECT r.RegionName, c.CountryName, (e.LastName + ', ' + e.FirstName) AS EmployeeName, (et.Title + ' ' + CAST(e.Level AS VARCHAR)) AS JobTitle, e.Salary FROM Regions r INNER JOIN Countries c ON r.RegionID = c.RegionID INNER JOIN Employees e ON c.CountryID = e.CountryID INNER JOIN EmployeeTitles et ON e.TitleID = et.TitleID ORDER BY r.RegionName, c.CountryName, e.LastName, et.Title, e.Salary;
内容的提问来源于stack exchange,提问作者Ben Smallwood

