SQL查询错误语法不正确

时间:2014-09-03 03:54:43

标签: sql

我正在尝试以下查询,但我收到的错误就像SqlDataReader reader = command.ExecuteReader上的语法不正确..请纠正我错在哪里

string querystring = "SELECT ImageName FROM dbo.ProfilePic WHERE UserName = @UserName & IsActive = 'Y' order by ID Desc";
            SqlCommand command = new SqlCommand(querystring, con);
            command.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());


            con.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}",
           reader[0]));

                ViewBag.ProfilePic = reader[0];
            }

            reader.Close();

更新了所有建议的答案

3 个答案:

答案 0 :(得分:0)

SQL不需要双等号。

SELECT ImageName FROM dbo.ProfilePic WHERE Username = @UserName

答案 1 :(得分:0)

SQL中,您不需要使用双等号来比较值,而&&是错误的,那么这是错误的:

string querystring = "select ImageName from dbo.ProfilePic where UserName == @UserName && IsActive == 'Y' order by ID descending";

这是真的:

string querystring = "select ImageName from dbo.ProfilePic where UserName = @UserName AND IsActive = 'Y' order by ID desc";

答案 2 :(得分:0)

            string querystring = "select ImageName from dbo.ProfilePic where UserName =       
            @UserName AND  IsActive = 'Y' order by ID DESC";
            // on sql compare oprator not need to '==' sign 
            SqlCommand command = new SqlCommand(querystring, con);
            command.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());
                con.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(String.Format("{0}",
               reader[0]));
                // when you assign reader value to any object you must assign while DataReader read not after DataReader close
                ViewBag.ProfilePic = reader[0];

                }

                reader.Close();

修改 试试

string querystring = "select ImageName from dbo.ProfilePic where UserName like '@UserName' AND  IsActive = 'Y' order by ID DESC";