在SQL字符串中使用引号

时间:2015-08-12 02:30:19

标签: sql vb.net

我正在尝试编写以下字符串以在Visual Basic中执行SQL语句:

 SELECT TOP 1 Questions.QuestionID, Questions.QuestionCategory & " : " & Questions.QuestionSubCategory AS Category FROM Questions WHERE (((Questions.QuestionDifficulty)=[?])) OR (((Questions.LastDateRevealed) Is Null)) OR ((Questions.LastDateRevealed)>=DateAdd("d",-7,Now())) ORDER BY Rnd(QuestionID);

但是,当我尝试使用双引号来转义引号时,我会对错误的字符串表示错误,并且基本上会破坏代码。我该如何写出来?

最终目标是它适合这样的一条线:

Dim QuestionConnectionQuery As New OleDb.OleDbCommand("", QuestionConnection)

将SQL出现在上述行的引号内。

2 个答案:

答案 0 :(得分:1)

你只需要在SQL中加倍双引号(这就是你如何在VB.NET中转义双引号)。

假设您帖子中的初始语句是您正在使用的SQL:

& " : " &将成为& "" : "" &DateAdd("d",-7,Now())将成为DateAdd(""d"",-7,Now())

完整陈述:

Dim QuestionConnectionQuery As New OleDb.OleDbCommand("SELECT TOP 1 Questions.QuestionID, Questions.QuestionCategory & "" :  "" & Questions.QuestionSubCategory AS Category FROM Questions WHERE (((Questions.QuestionDifficulty)=[?])) OR (((Questions.LastDateRevealed) Is Null)) OR ((Questions.LastDateRevealed)>=DateAdd(""d"",-7,Now())) ORDER BY Rnd(QuestionID);", QuestionConnection)

答案 1 :(得分:0)

您可以在此处使用SQL CONCAT。

SELECT TOP 1 Questions.QuestionID, 
Questions.QuestionCategory + ' : ' + 
Questions.QuestionSubCategory AS Category 
FROM Questions 
WHERE (((Questions.QuestionDifficulty)=[?])) 
OR (((Questions.LastDateRevealed) Is Null)) 
OR ((Questions.LastDateRevealed)>=DateAdd("d",-7,Now())) 
ORDER BY Rnd(QuestionID);

即使这也行得正常

SELECT TOP 1 Questions.QuestionID,CONCAT(Questions.QuestionCategory ,':', Questions.QuestionSubCategory) AS Category 
FROM Questions 
WHERE (((Questions.QuestionDifficulty)=[?])) 
OR (((Questions.LastDateRevealed) Is Null)) 
OR ((Questions.LastDateRevealed)>=DateAdd("d",-7,Now())) 
ORDER BY Rnd(QuestionID);