例外:参数长度超过C#中128个字符的限制

时间:2015-03-25 11:00:03

标签: c# sql-server wcf exception

我试图使用WCF服务在SQLServer中插入值。 有5行要插入。

它给予例外:

  

参数的长度超过128个字符的限制

是的,它的长度超过128个字符。但我声明了NVarChar(4000)的大小。

我已经搜索过这个网站,以及其他网站了解并摆脱这种异常

MedicineTestName = "1,crocin,2,aspirin,2,naproxen,3,ibuprofen,3,Ketaprofen";

代码:

public static string InsertHistory(string PatientId, string MedicineTestName, string CreateBy)
    {
       DataSet objdata;
       object objSubjectReader = new object();
        try
        {
               StringBuilder sb = new StringBuilder();

            string[] wordswithcomma = MedicineTestName.Split(',');

            for (int i = 0; i < wordswithcomma.Length -1 ; i=i+2)
            {

                string MedicineType = wordswithcomma[i];
                string MedicineName = wordswithcomma[i + 1];

                sb.Append("insert into tblMedicineHistory values(" + PatientId + "," + "'" + MedicineName + "'" + "," + MedicineType + ",GETDATE()," + "'" + CreateBy + "'" + ",GETDATE(),0);");

            }
            string sbo = sb.ToString();

            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter(sbo, System.Data.SqlDbType.NVarChar, 4000);
            param[0].Value = sbo;

           objdata = SqlHelper.ExecuteDataset(ConString, CommandType.StoredProcedure, "SP_MedicineHistory", param);


           return JsonConvert.SerializeObject(objdata, Newtonsoft.Json.Formatting.Indented);
            //return sbo;
        }
        catch (SqlException ex)
        {

            return objSubjectReader.ToString();
        }

    }
谢谢。

1 个答案:

答案 0 :(得分:3)

我认为它抱怨参数的名称;您传递sbo作为参数名称,但sbo完全合成的TSQL ,它将是...... long。注意:您的SQL完全不安全 - 如何参数化SQL!

正确参数化单行的SQL将类似于:

const string sql = @"
insert into tblMedicineHistory (PatientID, MedicineName, MedicineType, ...)
values(@patientId, @medicineName, @medicineType, ...)";

var args = new[] {
    new SqlParameter("@patientId", PatientId),
    new SqlParameter("@medicineName", MedicineName),
    new SqlParameter("@medicineType", MedicineType),
    ...
}