0

我的 C# 程序中有 sql 查询来搜索或过滤一些记录。当我使用撇号传递字符串值时,它会在我的 C# 程序中引发一些不正确的关键字错误。

我的示例输入

String Val= Tests of the 'convergence hypothesis' :  a critical note /  Daniel Cohen.

我的查询

string MySqlQry="SELECT bc.BibId,
   stuff(
           (SELECT ' ' + bsc.NormValue + ''
            FROM BibContents bsc
            WHERE bsc.bibid = bc.bibid
              AND bsc.tagno = '245'
            ORDER BY bsc.Sfld
            FOR xml path(''), root('MyString'), TYPE).value('/MyString[1]','varchar(max)') , 1, 1, '') AS Title,
   stuff(
           (SELECT ' ' + bsc.NormValue + ''
            FROM BibContents bsc
            WHERE bsc.bibid = bc.bibid
              AND bsc.tagno = '020'
            ORDER BY bsc.Sfld
            FOR xml path(''), root('MyString'), TYPE).value('/MyString[1]','varchar(max)') , 1, 1, '') AS ISBN,
   stuff(
           (SELECT ' ' + bsc.NormValue + ''
            FROM BibContents bsc
            WHERE bsc.bibid = bc.bibid
              AND bsc.tagno = '250'
            ORDER BY bsc.Sfld
            FOR xml path(''), root('MyString'), TYPE).value('/MyString[1]','varchar(max)') , 1, 1, '') AS Edition,
   stuff(
           (SELECT ' ' + bsc.NormValue + ''
            FROM BibContents bsc
            WHERE bsc.bibid = bc.bibid
              AND bsc.tagno = '260'
            ORDER BY bsc.Sfld
            FOR xml path(''), root('MyString'), TYPE).value('/MyString[1]','varchar(max)') , 1, 1, '') AS Publisher,
   (SELECT top(1) Value FROM BibContents
   WHERE TagNo='100'
   AND Sfld='a'
   AND BibId=bc.BibId) AS Author
   FROM BibContents bc
   WHERE (bc.NormValue LIKE '" + Val + "%'
   OR bc.NormValue LIKE '% " + Val + "%')
   AND bc.TagNo='245'";

model = db.ExecuteStoreQuery<PoDetails>(MySqlQry).ToList();

感谢您提供解决方案的任何帮助。

4

1 回答 1

0

您只需要转义单引号。

http://blog.sqlauthority.com/2008/02/17/sql-server-how-to-escape-single-quotes-fix-error-105-unclosed-quotation-mark-after-the-character-string/

在将“Val”插入语句之前,请执行以下操作:

Val = Val.Replace("'", "''");

于 2013-10-08T11:20:46.947 回答