找到你要的答案

Q:Why is the SQL query throwing an error

Q:为什么是SQL查询语句抛出一个错误

code:

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();
    }
}

I keep getting an error in this line: cmd.ExecuteReader();

Error:

Incorrect syntax near '\'.

How can I resolve the error.

代码:

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();
    }
}

我一直在这条线得到一个错误:executereader() CMD;

误差:

Incorrect syntax near '\'.

我该如何解决这个错误。

answer1: 回答1:

You added @ at the beginning of the command string so it will be somthing like that :

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

So remove \"" and \"" from the command string. You also wrapped the column names by ' that should be removed

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

You did not use the alias so you can remove it,

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

你说“在命令字符串的开始,它会是这样的:

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";
answer2: 回答2:

When using the "@" symbol in c# strings, you use don't escape quotes with a slash, you use two in a row like: "" Your other problem is the single quotes, remove them all, you do not surround field names with quotes, just literal text.

When using the "@" symbol in c# strings, you use don't escape quotes with a slash, you use two in a row like: "" Your other problem is the single quotes, remove them all, you do not surround field names with quotes, just literal text.

c#  sql  sql-server-2008