簡體   English   中英

字符串或二進制數據將被截斷…

[英]String or Binary Data Would be Truncated…

在我的項目中,我正在使用“隨機數”生成器函數生成一個隨機字符,並將其存儲在數據庫中,該數字會正確生成,但是在插入數據期間會引發異常“字符串或二進制數據將被截斷”

我的代碼:

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

檢查您存儲的過程。 您可能忘記了在參數上指定長度。 例如。 @ p1 nvarchar(1000)

數據庫中存在的列變量的大小小於我要保存的變量數據的大小,因此我得到了錯誤字符串或二進制數據將被截斷的信息

我已經通過增加數據庫中變量的大小解決了該錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM