在我的項目中,我使用隨機數生成器函數生成一個隨機字符並將其存儲在數據庫中,數字生成正確,但在插入數據期間,它拋出異常「字符串或二進制數據將被截斷」字符串或二進制數據將被截斷...
我的代碼:
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
此消息表示您要填寫列中的內容不適合。所以你可能在你的一列中有超過100個字符。計算您的變量並將其輸出,然後將其插入到數據庫中以查看。 – YvesR
@Yvesr我用Clientmessaging檢查過它,Randomnumbergenerator函數只生成四個字符,例如:sDfT – Rajesh
數據大於字段長度不是很明顯嗎? –