如果第一个查询结果=第二个查询结果

时间:2015-01-18 19:13:33

标签: c# sql asp.net asp.net-mvc visual-studio-2010

我正在尝试使用If语句进行两次查询。如果查询一=查询2

string select = "Select ProfileId from Project_list Where ProjectId = @ProjectId";
        using (SqlConnection myConnection = new SqlConnection(connectionString))
        {

            myConnection.Open();
            SqlCommand myCommand = new SqlCommand(select, myConnection);
            myCommand.Parameters.AddWithValue("@ProjectId", querystring);
            object Project_listResult = myCommand.ExecuteScalar();
        }


        string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (@UserId)";
        using (SqlConnection myConnection = new SqlConnection(connectionString))
        {
            myConnection.Open();
            SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
            myCommand.Parameters.AddWithValue("@UserId", currentUserId);
            object User_profileResult= myCommand.ExecuteScalar();
        }


        if (Project_listResult == User_profileResult)
        {
            addFollowerButton.Visible = true;

        }

这是我的代码,但是没有用。

错误18名称' Project_listResult'在当前

中不存在

错误19名称' User_profileResult'在当前

中不存在

2 个答案:

答案 0 :(得分:2)

您必须在外部定义两个值,以便使用它们。现在你在使用中定义了两个值,所以这些值只在under的范围之内,并且在那之外不可用,所以你得到了那个错误。

一个简单的建议是避免使用属于不同语言的关键字,因为您使用select作为变量名。这有助于提高可读性并增加混淆。

Refer

object Project_listResult = null;
object User_profileResult = null;
using (SqlConnection myConnection = new SqlConnection(connectionString))
        {

            myConnection.Open();
            SqlCommand myCommand = new SqlCommand(select, myConnection);
            myCommand.Parameters.AddWithValue("@ProjectId", querystring);
            Project_listResult = myCommand.ExecuteScalar();
        }


        string getProfileId = "SELECT ProfileId FROM User_Profile WHERE UserId = (@UserId)";
        using (SqlConnection myConnection = new SqlConnection(connectionString))
        {
            myConnection.Open();
            SqlCommand myCommand = new SqlCommand(getProfileId, myConnection);
            myCommand.Parameters.AddWithValue("@UserId", currentUserId);
            User_profileResult= myCommand.ExecuteScalar();
        }


        if (Project_listResult.Equals(User_profileResult))
        {
            addFollowerButton.Visible = true;

        }

答案 1 :(得分:0)

如果我了解你,你会尝试比较这些物品。所以你必须尝试

 if (Project_listResult.Equals(User_profileResult))
            addFollowerButton.Visible = true;

http://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx