0

How can I skip or say "error" on SQL server when the data does not match with data type? such as ID has nchar(2) on SQL server and I have csv file that one of data is '1234' for ID. How can I have error sign or error report for that data in SQL server. It is ok that I can have separate excel file about all the errors. I just want to know which data got error.

And make the script without stopping even there is an error.

Here is my script

$today = (get-date).Date
$DataImport = Import-Csv -Path (Get-ChildItem filename | where { $_.CreationTime.Date -eq $today } )    
$DataTable = Out-DataTable -InputObject $DataImport
write-DataTable -serverInstance servername -Database DBname -TableName Table name -Data $DataTable

Functions Out-DataTable and Write-DataTable have been defined.

1

2 Answers 2

1

You can use TRY and CATCH.

$today = (get-date).Date
TRY
{
$DataImport = Import-Csv -Path (Get-ChildItem filename | where { $_.CreationTime.Date -eq $today } )    
$DataTable = Out-DataTable -InputObject $DataImport
write-DataTable -serverInstance servername -Database DBname -TableName Table name    -Data $DataTable
}
CATCH 
{     
$_.Exception.Message
"PS code here that writes error to txt or to excel."
}
Sign up to request clarification or add additional context in comments.

Comments

0

Write-DataTable function is using the the .NET SqlBulkCopy class http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx, unlike the T-SQL BULK INSERT command or some data loading utilities like SSIS, there's isn't an option to commit some rows and log error rows. You could play with changing the -BatchSize parameter to 1 instead of 50,000, this way it will commit each row and instead of rolling back entire batch and you can catch the exception. Note: This will be slower for large datasets.

Another solution is to use the T-SQL BULK INSERT command specifying an error file:

$query = "BULK INSERT dbname..table FROM 'C:\temp\test.csv' WITH (FIRSTROW = 2, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', ERRORFILE = 'C:\temp\test.err')"

Then call the query using invoke-sqlcmd or sqlcmd.exe.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.