我在 'nchar' 附近遇到错误语法错误

I have a error on Incorrect syntax near 'nchar'

错误是说 nchar 附近的语法不正确,这就是 visual studio 建议的

错误提示第 31 行:

An expression of non-boolean type specified in a context where a condition is expected, near 'Name'. int temp = Convert.ToInt32(com.ExecuteScalar());

我的代码如下

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
       SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);

       conn.Open();
       string checkuser = "select count(*) from [Table] where User Name=@User Name";
       SqlCommand com = new SqlCommand(checkuser, conn);

       com.Parameters.Add("@User Name", SqlDbType.NChar, 20).Value = TextBoxUN.Text;
       int temp = Convert.ToInt32(com.ExecuteScalar());           

       if (temp == 1)
       {
           Response.Write(" USER ALREADY EXISTS ");
       }


       conn.Close(); 
    }
}

如果您使用的数据库对象和参数名称超过一个单词,则需要使用方括号,如 [User Name]

也可以使用 using statement 来处理你的 SqlConnectionSqlCommand

using(SqlConnection conn = new SqlConnection(connString))
using(SqlCommand com = conn.CreateCommand())
{
    com.CommandText = "select count(*) from [Table] where [User Name] = @UserName";
    com.Parameters.Add("@UserName", SqlDbType.NChar, 20).Value = TextBoxUN.Text;
    conn.Open();
    int temp = Convert.ToInt32(com.ExecuteScalar()); 
}

作为一种最佳做法,不要为您的 table 或列名称使用多个词。

试试看

string checkuser = "select count(*) from [Table] where [User Name]=@UserName"
SqlCommand com = new SqlCommand(checkuser, conn);

       com.Parameters.Add("@UserName", SqlDbType.NChar, 20).Value = TextBoxUN.Text;

如果列名中有空格,您应该将列名括在大括号中。所以列名用户名应该放在方括号'[]'中,对于参数名“@User Name”,我认为它也不会接受它,你也应该删除参数名中的空格。