【问题标题】:Why is the SQL query throwing an error为什么 SQL 查询会抛出错误
【发布时间】:2015-08-14 14:28:40
【问题描述】:

代码:

string qr = @"select 'TheCode','CodeDesc' from [dbo].[Table1] as \""Table1\"" order by 'CodeDesc'";
using (SqlConnection conn = new SqlConnection(connstring))
{
    try
    {
        conn.Open();

        SqlCommand cmd = new SqlCommand(qr, conn);

        SqlDataReader sdr = cmd.ExecuteReader();
    }
    catch (Exception ex) // Incorrect syntax near '\'.
    {
        string error = ex.Message;
    }
    finally
    {
        conn.Close();
    }
}

我在这一行中不断收到错误:cmd.ExecuteReader();

错误:

Incorrect syntax near '\'.

我该如何解决这个错误。

【问题讨论】:

  • 你能把你的错误信息放在问题中吗?
  • 它在代码中,但如果不清楚,我也可以在问题中添加它。
  • 对了,你知道 SqlCommand 和 SqlDataReader 也像 SqlConnection 一样是 IDisposable 的,你应该用 using 子句包围它们吗?
  • @DDavid 是的。谢谢。

标签: c# sql sql-server-2008


【解决方案1】:

您在命令字符串的开头添加了@,所以它会是这样的:

select distinct 'TheCode','CodeDesc' from [dbo].[Table1] as \""Table1\"" 
order by 'CodeDesc'";

所以从命令字符串中删除\""\""。您还用' 包装了应该删除的列名

string strQryDDL = @"select distinct TheCode,CodeDesc from [dbo].[Table1] as t 
order by CodeDesc";

你没有使用别名,所以你可以删除它,

string strQryDDL = @"select distinct TheCode,CodeDesc from [dbo].[Table1] 
order by CodeDesc";

【讨论】:

  • 现在我得到这个错误:Invalid object name 'dbo.Table1'.
  • 其实在这种情况下给表取别名有什么意义吗?
  • 你的数据库中有table1吗?
  • 抱歉使用了错误的数据库。我现在收到此错误:A constant expression was encountered in the ORDER BY list, position 1.
  • 谢谢。为你+1。我能够填充 DropDownList,。
【解决方案2】:

在 c# 字符串中使用“@”符号时,不要使用斜线转义引号,而是连续使用两个,例如:“” 您的另一个问题是单引号,将它们全部删除,您不要用引号将字段名称括起来,而只是文字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2019-06-13
    • 2021-06-17
    • 2015-02-25
    相关资源
    最近更新 更多