title: Upload to SQL Server 2012 via ODBC dbWriteTable - Error "String data, right truncation" column type chr vs. nvarchar(50)
body: <p>I try to insert a data.table from R to SQL Server 2012 database:</p>
  
  <pre><code>library(data.table)
  library(odbc)
  library(dplyr)
  
  upload.data &lt;- data.table(readxl::read_excel(path = uploadfile.file, sheet = 
  sheet_no, skip = skip_rows), col_names = TRUE)
  
  odbcChannel &lt;- dbConnect(odbc::odbc(), "SQL")
  
  dbWriteTable(odbcChannel, "Table_Name", upload.data, append = TRUE, overwrite = FALSE, row.names=FALSE, encoding = "latin1")
  </code></pre>
  
  <p>The columns in the data table are of type chr. The columns of the target table in SQL Server are of type <code>varchar(50)</code>.</p>
  
  <p>My understanding is that chr would be uploaded as <code>varchar(255)</code>. Because of this I will get the error: </p>
  
  <blockquote>
    <p>Error in result_insert_dataframe(rs@ptr, values) :<br>
    nanodbc/nanodbc.cpp:1587: 22001: [Microsoft][ODBC SQL Server Driver]String data, right truncation</p>
  </blockquote>
  
  <p>How can I change the columns in R to match the specific needs of the table in my database?</p>
  
  <p>If there is content in the column which would not fit into the database table I would like that the information gets cut away. </p>
  
  <p>One solution: upload the data table into a new table into the server and than edit the types to match with:</p>
  
  <pre><code>dbSendStatement(odbcChannel,"ALTER  TABLE Table_Name
                               ALTER COLUMN Batch_Name Nvarchar(50)")
  </code></pre>
  
  <p>After this I could insert the data in the target table. But this seems quite complicated especially if every column in the database has a different type.</p>
  
  <p>Best regards and my thanks,</p>
  
  <p>HP</p>