我使用查询但不抛出异常c#时不起作用的变量

时间:2017-07-24 13:20:17

标签: c# sql asp.net .net sql-server

当我尝试使用query6运行它时 - >那个[religion] = @religionVar它只返回数据表中的表格标题但是当我对查询5这样做时它会把我带回到表格中

string query5 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '5' AND([religion] = @religionVar OR[religion] = '4')";
string query6 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '6' AND([religion] = @religionVar OR[religion] = '4')";

如果我这样做,query6返回表格

string query5 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '5' AND([religion] = @religionVar OR[religion] = '4')";
string query6 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '6' AND([religion] = '1' OR[religion] = '4')";

我试着运行它mssql并且它的工作正常但我无法解释为什么它首先工作而不能在另一个工作

string query5 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '5' AND([religion] = @religionVar OR[religion] = '4')";
string query6 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '6' AND([religion] = '1' OR[religion] = '4')";

using (SqlConnection con = new SqlConnection(@"Data Source=CATISERVER1\SQLEXPRESS;Initial Catalog=dsa;Persist Security Info=True;User ID=mcsager;Password=*******"))
{
    try
    {                    
        SqlCommand cmd5 = new SqlCommand(query5, con);
        cmd5.Parameters.AddWithValue("@religionVar", 1);
        SqlCommand cmd6 = new SqlCommand(query6, con);
        cmd6.Parameters.AddWithValue("@religionVar", 1);
        SqlDataAdapter adpter5 = new SqlDataAdapter(cmd5);
        adpter5.Fill(MyAppManager.ChangeFactorWeightsInstance.DtDistrict_5);
        SqlDataAdapter adpter6 = new SqlDataAdapter(cmd6);
        adpter6.Fill(MyAppManager.ChangeFactorWeightsInstance.DtDistrict_6);
    }
    catch{}
}

1 个答案:

答案 0 :(得分:0)

您在一个连接上使用相同的变量两次。在sql中为每个查询提供自己的变量。我拿了你的代码,用@ religiongvar1和@ religionvar2替换了@religionvar。

string query5 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '5' AND([religion] = @religionVar1 OR[religion] = '4')";
string query6 = "SELECT * FROM[PhoneTableSql] WHERE[district] = '6' AND([religion] = @religionVar2 OR[religion] = '4')";

    using (SqlConnection con = new SqlConnection(@"Data Source=CATISERVER1\SQLEXPRESS;Initial Catalog=dsa;Persist Security Info=True;User ID=mcsager;Password=*******"))
    {
        try
        {                    
            SqlCommand cmd5 = new SqlCommand(query5, con);
            cmd5.Parameters.AddWithValue("@religionVar1", 1);
            SqlCommand cmd6 = new SqlCommand(query6, con);
            cmd6.Parameters.AddWithValue("@religionVar2", 1);

            SqlDataAdapter adpter5 = new SqlDataAdapter(cmd5);
            adpter5.Fill(MyAppManager.ChangeFactorWeightsInstance.DtDistrict_5);
            SqlDataAdapter adpter6 = new SqlDataAdapter(cmd6);
            adpter6.Fill(MyAppManager.ChangeFactorWeightsInstance.DtDistrict_6);
        }
        catch{}
    }