当我插入数据时,SQL服务器删除值之前的空间

本文关键字:删除 空间 服务器 SQL 插入 数据 | 更新日期: 2023-09-27 18:17:48

当我使用SqlCommand插入数据时,它还会在我刚刚插入的值之前添加空间。如何避免添加空格?

插入查询代码:

SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] 
    ([Contract_Id],[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept],[Start_date],[Expiration_Date],[TypeofContract],[Contact_Person],[Contact_No],FileName,FileData,FileType) 
    VALUES (' " + TextBox1.Text + "',' " + TextBox2.Text + "',' " + TextBox3.Text + "',' " + TextBox4.Text + "',' " + TextBox5.Text + "',' " + DepartmentTextBox.SelectedValue.ToString() + "',' " + TextBox7.Text + "',' " + TextBox8.Text + "',' " + TextBox9.Text + "',' " + TextBox10.Text + "',' " + TextBox11.Text + "',@Name,@Data,@Type)", con);

当我插入数据时,SQL服务器删除值之前的空间

当然,当您使用字符串连接来构建命令文本时,任何类型的问题都会出现。在这种情况下,您无意中在控件值之前添加了一个空格。
如果使用了参数化查询,就不会出现这个问题

  SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] " + 
     "([Contract_Id],[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept]," + 
     "[Start_date],[Expiration_Date],[TypeofContract],[Contact_Person]," + 
     "[Contact_No],FileName,FileData,FileType) VALUES (" + 
     "@cid, @name, @desc, @cby, @vname, @rdept, @stdate, @expdate, " + 
     "@tc, @cp, @cno, @file, @fdate, @ftype",con)
  SqlParameter p = new SqlParameter("@cid", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text));
  cmd.Parameters.Add(p);
  .... and so on for the other parameters required

顺便说一下,请记住,如果您有一个IDENTITY列,您不应该尝试在该列中插入任何东西(这里特别可疑的是Contract_ID)

它正在插入空格,因为您在查询字符串中有额外的空格。我将"',' "更改为"','":

SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] ([Contract_Id],
 [Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept],[Start_date],
 [Expiration_Date],[TypeofContract],[Contact_Person], Contact_No],FileName,FileData,FileType) 
 VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + 
 TextBox4.Text + "','" + TextBox5.Text + "','" + DepartmentTextBox.SelectedValue.ToString() 
 + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + 
 TextBox10.Text + "','" + TextBox11.Text + "',@Name,@Data,@Type)", con);