Try to debug it as follows (Assuming you are using Visual Studio):
1. Set a breakpoint at the following line and run your program in debug mode.
cmd.CommandText = ...
2. When the breakpoint hits this line, view the value of cmd.CommandText (Using watch or Immediate window) and copy the value.
3. Run the SQL in the SQL Server Management Studio (Or, the query window of your database server).
4. See what happens. If it does not run correctly, try to analyze the SQL and find problem. Make sure the SQL is correct.
5. Now, find the difference between the correct SQL and the SQL that you copied from the cmd.CommandText property from the breakpoint. Fix the code that is generating the wrong part of the SQL.
Hopefully, your problem will be solved
Best wishes