字符串或二进制数据将被截断...

时间:2013-05-27 05:44:02

标签: c# sql-server

在我的项目中,我使用随机数生成器函数生成随机字符并将其存储在数据库中,数字生成正确但在插入数据期间抛出异常“字符串或二进制数据将是截短的”

我的代码:

protected void trigger()
{  
    try
    {
        DataSet ds = ExamManagement.SP.table2_SP_Selectall().GetDataSet();
        if (ds.Tables[0].Rows.Count > 0)
        {
            string a = RandomNumberGenerator(4);
            string b = RandomNumberGenerator(4);
            string c = RandomNumberGenerator(4);
            ExamManagement.SP.table1_insert(a,b,c).Execute();
        }
    }
    catch (SqlException ex)
    {
        ClientMessaging("Error :"+ex);
    }
}

public static string RandomNumberGenerator(int length)
{
    System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create();

    char[] chars = new char[length];

    //based on your requirment you can take only alphabets or number 
    string validChars = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXzZ";
    byte[] bytes = new byte[length-1];
    for (int i = 0; i < length; i++)
    {

        rng.GetBytes(bytes);

        Random rnd = new Random(bytes[0]);

        chars[i] = validChars[rnd.Next(validChars.Length)];

    }

    return (new string(chars));
}

我的SQL Server表格结构:

  Column1, nvarchar(100),null
  Column2, nvarchar(100),null
  Column3, nvarchar(100),null

我的改变存储过程是,

   Create Procedure Table1_insert    
   (    
    @col1 varchar(max),    
    @col2 varchar(max),    
    @col3 varchar(max)   
   )    
  as    
 BEGIN    
 BEGIN TRY    
 Insert into Table1(Column1,Column2,Column3) values (@col1,@col2,@col3)    
END TRY    
BEGIN CATCH                    
IF @@TRANCOUNT > 0                    
ROLLBACK                    
DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int                    
SELECT @ErrMsg = ERROR_MESSAGE(),                    
@ErrSeverity = ERROR_SEVERITY()                    
RAISERROR(@ErrMsg, @ErrSeverity, 1)                    
END CATCH     
END

2 个答案:

答案 0 :(得分:0)

检查您的存储过程。您可能忘了在参数上指定长度。例如。 @ p1 nvarchar(1000)

答案 1 :(得分:0)

数据库中存在的列变量大小比我发送的可变数据小,因此我得到错误字符串或二进制数据将被截断

我通过增加DB中变量的大小来解决错误