我从下面的代码所示的SQL命令中收到语法错误。错误发生在ExecuteReader
行,说
关键字“ JOIN”附近的语法不正确。
我不知道为什么会引发语法错误,该命令在SQL Server中工作得很好。这是代码:
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);
}
谢谢!
答案 0 :(得分:8)
空白。请记住:
"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
";
这不仅使编写代码更加容易,而且您可以轻松地在SSMS和devenv之间复制/粘贴,而无需添加引号等。
答案 1 :(得分:1)
在"
前添加空格,否则将串联为单个单词示例
"FROM Roster" +
"INNER JOIN VideoGames" +
将变为FROM RosterINNER JOIN VideoGames
,因此请在"
之前和"
之后添加空间
示例
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 ";