c# - SQL从nVarchar到int的转换报错

标签 c# sql sql-server

错误:

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  i.topic_id=@topicid";
    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();
    }
}

谁能告诉我哪里错了?任何帮助将不胜感激..请尽快回复..提前致谢..

最佳答案

您传递的是整个查询中的而不是此处这一行中的主题 id

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

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

但它失败的原因是因为您实际上是在尝试通过传入查询字符串来比较 Stringint

关于c# - SQL从nVarchar到int的转换报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20278791/

相关文章:

c# - ASP.NET SqlMembership Provider 允许多个用户同名

mysql - MySQL 中的平均 datediff

c# - 在 C# SQL 查询中,Parameters.Add() 比直接在查询中嵌入值有什么优势?

sql - Visual Studio 2013 SQL Server 数据库项目构建失败

c# - 保持用户长时间登录到 ASP.NET 5 网站

c# - 如何防止全屏表格覆盖任务栏?

c# - 如何在不使用旧版驱动程序的情况下在 MongoDB C# 驱动程序版本 2.1 中实现 CommandDocument

MYSQL 数据库 - 如何使用存储应显示的订单项目的 "order"列 - 按另一列分组

sql - 如何确定导致INSERT中重复输入错误的表行?

sql-server - 德尔福EMS FireDAC : How to pass parameter from client to server using EMS?