c# SqlDataReader 抛出语法错误,但命令在 SQL 服务器中运行正常?

c# SqlDataReader throwing syntax error, but the command runs fine in SQL Server?

我的 SQL 命令出现语法错误,如下面的代码所示。错误发生在 ExecuteReader 行,表示

Incorrect syntax near the keyword 'JOIN'.'

我不知道为什么会抛出语法错误,该命令在 SQL 服务器中运行良好。这是代码:

private void button1_Click(object sender, EventArgs e)
{
    SqlCommand sqlcomViewSmashRoster;
    SqlDataReader dataReader;
    String strSql, strOutput ="";

    strSql = "SELECT Roster.CharacterName, Roster.TotalTournamentsParticiaped, Roster.TotalWins, Roster.TotalLosses, Roster.Championships, Roster.InjuriesCaused, Roster.Injured" +
             "FROM Roster" +
             "INNER JOIN VideoGames" +
             "ON VideoGames.VideoGame_ID = Roster.VideoGame_ID" +
             "WHERE roster.VideoGame_ID = 2";

    cnn.Open();

    sqlcomViewSmashRoster = new SqlCommand(strSql, cnn);

    dataReader = sqlcomViewSmashRoster.ExecuteReader();

    while (dataReader.Read())
    {
        strOutput = strOutput + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "\n";
    }

    cnn.Close();

    MessageBox.Show(strOutput);
}

谢谢!

空格。请记住:

"abc" +
"def"

"abcdef"

逐字字符串文字是您的朋友:

strSql = @"
SELECT Roster.CharacterName, Roster.TotalTournamentsParticiaped, Roster.TotalWins,
       Roster.TotalLosses, Roster.Championships, Roster.InjuriesCaused, Roster.Injured
FROM Roster
INNER JOIN VideoGames
ON VideoGames.VideoGame_ID = Roster.VideoGame_ID
WHERE roster.VideoGame_ID = 2
";

这不仅首先更易于编码,而且您可以轻松地 copy/paste 在 SSMS 和 devenv 之间,而无需添加引号等。

"之前添加space否则它将连接为单个单词示例

"FROM Roster" +
             "INNER JOIN VideoGames" +

会变成FROM RosterINNER JOIN VideoGames所以在"之前和"之后添加space

例子

strSql = "SELECT Roster.CharacterName, Roster.TotalTournamentsParticiaped, Roster.TotalWins, Roster.TotalLosses, Roster.Championships, Roster.InjuriesCaused, Roster.Injured " +
             " FROM Roster " +
             " INNER JOIN VideoGames " +
             " ON VideoGames.VideoGame_ID = Roster.VideoGame_ID " +
             " WHERE roster.VideoGame_ID = 2 ";