rubyscript.rb
require 'tiny_tds'
require 'csv'
#For connecting into mssql database
def establish_connection
@client = TinyTds::Client.new username: 'username', password: 'password', host:
'hostid', database: 'database_name', azure: false
puts("Connection secured")
end
#For creating a table
def create_table
sql = "CREATE TABLE ABBTesting102(first_name VARCHAR(20), email VARCHAR(20));"
@data=@client.execute(sql)
puts("Table created Successfully")
end
#For Importing to mssql using bcp
def bcp_importing
puts("Inside bcp importing function")
sql_query = '
BULK INSERT ABBTesting102
FROM {students.csv}
WITH (FORMATFILE = {format_file.fmt});'
@datas = @client.execute(sql_query)
puts("Importing Successfully Completed")
end
format_file.fmt
14.0
2
2 SQLCHAR 0 70 "," 1 first_name ""
3 SQLCHAR 0 70 "," 2 email ""
Students.csv
id,first_name,email
1,sam,sam@gmail.com
2,Emma,emma@gmail.com
3,Max,Max@gmail.com
This is the sample data. When I tried with this rubyscript, the data is not being inserted. What I'm trying to do is that skip the first column while inserting into the SQL Server using BCP. I tried inserting without using BCP and format file and it seems to be inserting, but I'm trying to insert this student.csv while using the BCP. I want to skip the id column while inserting it into SQL Server and I don't want the id to be inserted. The SQL Server credentials given are dummy. Can someone help me insert this CSV into a SQL Server table using BCP while skipping the first column which is the identity column in ruby.
