I need to move table from an Azure SQL database to another database Firstly, I have exported data from table by using below query:
select contract_id, contractor_name, plan_id, quantity, format(exec_date, 'yyyyMMddHHmmssffff') as exec_date, initial_plan, contract_status, backup_disksize, format(register_date, 'yyyyMMddHHmmssffff') as register_date, format(update_date, 'yyyyMMddHHmmssffff') as update_date from [dbo].[contract_management]
And then, I have used a BCP query to import data to my new database:
bcp contract_management in Query3.csv -S dbaas-share-gs-sql.database.windows.net -d dbaas-tenant-gs-sqldb-tsdvdev01 -U owner_tsdvdev01 -P 12345678ABC-q -c -t ","
And this error happen
SQLState = 22008, NativeError = 0 Error = [Microsoft][ODBC Driver 18 for SQL Server]Invalid date format
I also tried other queries when export data like:
select contract_id, contractor_name, plan_id, quantity, format(exec_date, 'yyyyMMdd') as exec_date, initial_plan, contract_status, backup_disksize, format(register_date, 'yyyyMMdd') as register_date, format(update_date, 'yyyyMMdd') as update_date from [dbo].[contract_management]
But this error still happened. What should I do to solve this problem? Thanks a lot
3条答案
按热度按时间wwwo4jvm1#
I believe BCP is unable to convert the format
yyyyMMddHHmmssffff
(which returns a value like this 202310310633130100) to adatetime
. Try using this format in your export query instead:yyyy-MM-dd HH:mm:ss.ffff
w1jd8yoj2#
The error is because when you export the data in the file it stored into the string format and when you import the data to table the table has column with data type datetime.
To workaround this issue you need to Use a staging table (table with all datatype varchar for date time column of destination table), AFAIK You will not be able to import that date format directly into a
datetime2
column with bcp. After loading data into staging table then cast the data into date time format and insert into destination.Insert the data from CSV file to this staging table.
Now insert the data from staging table to destination by converting to correct format.
OUTPUT:
chy5wohz3#
Excerpt from copying date values in the documenation:
bcp uses the ODBC bulk copy API. Therefore, to import date values into SQL Server, bcp uses the ODBC date format (yyyy-mm-dd hh:mm:ss[.f...]).
Use this T-SQL
FORMAT
function specification, assuming you need a precision of 4 like in your question:I successfully imported a text file with
datetime2
values in this format to Azure SQL Database withbcp
.