将nvarchar转换为int会导致错误消息

时间:2019-04-08 20:29:08

标签: c# sql-server

// https://www.codeproject.com/Questions/823002/How-to-clear-Request-Querystring

string url = context.Request.Url.AbsoluteUri; // Henter URL
string[] separateURL = url.Split('?'); // Splitter URL

NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(separateURL[0]); // Parameterne

string categoryId = queryString[0];  // Index 0 er categoryId

StringBuilder table = new StringBuilder();

con.Open();

SqlCommand cmd = new SqlCommand("uspPasteDataSubCategories", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@categoryid", categoryId);

SqlDataReader rd = cmd.ExecuteReader();

我收到此错误:

  

System.Data.SqlClient.SqlException:“将数据类型nvarchar转换为int时出错。”

这没有意义,因为数据库中的数据类型不是nvarchar

错误发生在:

SqlDataReader rd = cmd.ExecuteReader();

存储过程:

ALTER PROCEDURE [dbo].[uspPasteDataSubCategories]
    @categoryid INT
AS
    SELECT 
        SubCategory.subcategoryid, SubCategory.subcategoryname 
    FROM 
        Category, Category_SubCategory, SubCategory
    WHERE 
        Category.categoryid = @categoryid
        AND Category.categoryid = Category_SubCategory.categoryid
        AND SubCategory.subcategoryid = Category_SubCategory.subcategoryid

1 个答案:

答案 0 :(得分:0)

// The stored procedure is expecting an int as the parameter type
string url = context.Request.Url.AbsoluteUri; // Henter URL
string[] separateURL = url.Split('?'); // Splitter URL

NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString    (separateURL[0]); // Parameterne

string strCategoryId = queryString[0];  // Index 0 er categoryId

StringBuilder table = new StringBuilder();

con.Open();

SqlCommand cmd = new SqlCommand("uspPasteDataSubCategories", con);
cmd.CommandType = CommandType.StoredProcedure;
//Convert the string value to int
int categoryId = Int32.Parse(strCategoryId);

//Changed to use add verse AddWithValue. This way you can set the type for the parameter. Then you can set the value.
cmd.Parameters.Add("@categoryid", SqlDbType.Int);
cmd.Parameters["@categoryid"].Value = categoryId;

SqlDataReader rd = cmd.ExecuteReader();