2013-11-29 86 views
2

错误:SQL转换为INT错误

Conversion failed when converting the nvarchar value 'select TopicID from Topic where TopicName='Data Structure'' to data type int

代码:

public void BindGridview() 
{ 
    string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString; 

    SqlConnection sqlcon = new SqlConnection(strConnString); 
    sqlcon.Open(); 

    string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'"; 

    string strquery3 = "select i.name ,i.score from info as i,Topic as t where [email protected]"; 
    SqlCommand cmd = new SqlCommand(strquery3,sqlcon); 
    cmd.Parameters.AddWithValue("@topicid",strquery2); 

    cmd.Connection = sqlcon; 

    SqlDataReader dr;; 

    this.GridView1.DataSource =cmd.ExecuteReader(); 
    this.GridView1.DataBind(); 

    sqlcon.Close(); 
    } 
} 

谁能告诉我在哪里,我错了?任何帮助将不胜感激..请尽快回复..在此先感谢..

+0

“TopicID”的数据类型是什么? – Rohit

+0

@ user3048066:如果你想获得TopicID值并传递给其他查询存储过程,我认为是好的。 – VDN

+0

[踢坏的习惯:使用旧式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins。 aspx) - 用ANSI-** 92 ** SQL标准(超过** 20年**之前)停止使用旧式*逗号分隔的表*样式列表 –

回答

0

我想你想在cmd.Parameters.AddWithValue(“@ topicid”,strquery2);是由strquery2返回的值吗? ,如果首先执行此查询,则会生成主题ID,并且将使用此结果代替查询本身

这就是您要的?

+0

谢谢这么多Naresh先生的帮助..是的,这是正确的..你真的摇滚!我被困在这个问题三天..所以非常感谢帮助...谢谢! – user3048066

+0

我觉得错误的评论在这里;) –

+0

@NareshPansuriya先生,现在我在我的GridView中获得多个值..我只需要该值的核心相对它..例如像学生的名字是:A和B与分数8和9 ..但他们显示的值不止一个GridView ..你能否请帮助...在此先感谢! – user3048066

1

您传递的不是整个查询的主题ID在这条线在这里

cmd.Parameters.AddWithValue("@topicid",strquery2); 

然后走,作为一个参数,并将其添加到下面的查询。如果这是一个子查询,你可以总是先执行它,然后在参数中使用结果。

但它失败的原因是因为你基本上试图通过传递查询字符串来比较Stringint

0

你可以试着用下面的代码,我没有测试过,但它应该为你

public void BindGridview() 
{ 
    string strConnString = ConfigurationManager.ConnectionStrings["infoConnectionString"].ConnectionString; 
       SqlConnection sqlcon = new SqlConnection(strConnString); 
       sqlcon.Open(); 
       //Equal is not working when subquery return more records 
       string strquery2 = "select i.name ,i.score from info as i,Topic as t where i.topic_id in (select TopicID from Topic where [email protected])"; 

       SqlCommand cmd = new SqlCommand(strquery2, sqlcon); 
       cmd.Parameters.AddWithValue("@TopicName", ddltopic.SelectedItem.Text); 
       cmd.Connection = sqlcon; 
       SqlDataReader dr; ; 

       this.GridView1.DataSource =cmd.ExecuteReader(); 
       this.GridView1.DataBind(); 
       sqlcon.Close(); 
} 
+0

:答案没问题。但是,当我们在** SQL查询中使用**时,性能会降低。 – VDN

0

不是一个实际的答案工作,但评论太短了这一点。

此代码很容易受到SQL injection

string strquery2 = "select TopicID from Topic where TopicName='" + ddltopic.SelectedItem.Text+ "'"; 

试想一下,在未来的某人某一点(你或别人谁是修改代码)决定用组合框替换下拉列表?现在想象一下,有人进入这个文本的组合框:

'; TRUNCATE TABLE Topic; --' 

现在你的SQL服务器要做到这一点:

select TopicID from Topic where TopicName = ''; 
TRUNCATE TABLE Topic; --' 

Learn使用parameters