2013-11-29 88 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