VB.NET SQL query throws error on JOIN keyword

I’m stuck with a weird problem in my VB.NET app. My SQL query works fine in SSMS but fails in Visual Studio. Here’s what’s happening:

Dim query As String = "SELECT u.UserID AS 'ID', u.FirstName + u.LastName AS 'FullName', 
    FORMAT(u.BirthDate, 'dd/MM/yyyy') AS 'DOB', u.Gender, t.TeamName AS 'Team'
    FROM Users u
    JOIN Teams t ON u.TeamID = t.TeamID"

Dim cmd As New SqlCommand(query, connection)

When I run this, I get an error saying ‘Incorrect syntax near the keyword ON’. It’s driving me nuts! The query runs perfectly in SSMS, so I’m guessing it’s something to do with how I’m writing it in VB.NET.

Any ideas what I’m doing wrong here? Is there a special way to format JOIN statements in VB.NET that I’m missing? Help would be awesome!

Hey there! have u tried using string concatenation instead of multiline? sometimes that helps. like:

Dim query As String = "SELECT u.UserID AS ‘ID’, " & _
"u.FirstName + u.LastName AS ‘FullName’, " & _
"FORMAT(u.BirthDate, ‘dd/MM/yyyy’) AS ‘DOB’, u.Gender, " & _
“t.TeamName AS ‘Team’ FROM Users u JOIN Teams t ON u.TeamID = t.TeamID”

just curious, does this work better? let me know!

yo, have u tried wrapping ur column names in square brackets? sometimes VB.NET gets fussy bout that. like this:

Dim query As String = “SELECT [u].[UserID] AS ‘ID’, [u].[FirstName] + [u].[LastName] AS ‘FullName’…”

might solve ur problem. worth a shot, right?

I’ve encountered a similar issue before, and it’s often related to how Visual Studio interprets string literals. Try using a verbatim string literal by prefixing your query with @ to preserve line breaks and avoid potential escape character issues:

Dim query As String = @“SELECT u.UserID AS ‘ID’, u.FirstName + u.LastName AS ‘FullName’,
FORMAT(u.BirthDate, ‘dd/MM/yyyy’) AS ‘DOB’, u.Gender, t.TeamName AS ‘Team’
FROM Users u
JOIN Teams t ON u.TeamID = t.TeamID”

This approach should maintain the query structure exactly as you’ve written it. If that doesn’t resolve the issue, double-check that your connection string is correct and that you have the necessary permissions on the database. Also, ensure that the Teams table exists in the database you’re connecting to.