Brian
Brian

Reputation: 2051

Error: String or binary data would be truncated. The statement has been terminated

I'm trying to create a simple registration form, where data from textboxes etc. are input into a table called users:

user_id     int
username    nchar(20)
password    nchar(20)
... more columns

Code:

Dim Username As String = txtUsername.ToString
... more variable declarations

lblDOB.Text = DOB.ToString
lblDOB.Visible = True

Dim ProjectManager As String = "test"
... more constant declarations

Dim conn As New SqlConnection("...conn string...")

sqlComm = "INSERT INTO users(Username, Password, ...other columns...)" +
    "VALUES(@p1, @p2, ...other params...)"

conn.Open()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("@p1", Username)
... other AddWithValues

registerSQL.ExecuteNonQuery()

I'm getting this error message:

String or binary data would be truncated. The statement has been terminated.

Upvotes: 5

Views: 30705

Answers (3)

Vaibhav Chopade
Vaibhav Chopade

Reputation: 39

You are inserting string data in table which has more size than the size of column where you are storing it in table.

That is, you are passing Username to database which has size more than 20 characters.

Upvotes: 2

jojoseph
jojoseph

Reputation: 1

Please change nchar(20) to varchar(50)

Upvotes: 0

anon
anon

Reputation:

Yes, you are allowing any old string that people are typing in. You need to constrain each parameter to the maximum length allowed in that column. For example, if you don't want the error, you can truncate username to 20 characters or you can raise your own error when that parameter value is more than 20 characters. To truncate you could simply say:

Dim Username As String = txtUsername.ToString.Substring(0,20)

Or better yet, when you build your form, specify a MaxLength for the form field that matches the column in your table. Why let a user type in more than 20 characters if your table is only designed to hold 20?

As an aside, nchar is a terrible data choice for most of this data, unless usernames, passwords, etc. will always be exactly 20 characters. You should strongly consider nvarchar.

Upvotes: 7

Related Questions