Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does bcp output null when the column contains an empty string and empty string when the column is null?

This struck me as really weird behaviour and I spent a while checking for bugs in my code before I found this

"out copies from the database table or view to a file. If you specify an existing file, the file is overwritten. When extracting data, note that the bcp utility represents an empty string as a null and a null string as an empty string." (from http://msdn.microsoft.com/en-us/library/ms162802.aspx)

Obviously this allowed me to fix my problem but can anybody think of or does anybody know a reason why this is the case?

like image 513
David Hayes Avatar asked Oct 29 '09 15:10

David Hayes


People also ask

Why use NULL instead of empty string?

An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

Is empty string considered NULL in SQL?

"A string of zero length ('') is not equivalent to a NULL value. According to the ANSI SQL 1992 Transitional standard, a zero-length or empty string is not the same as NULL.

What does empty string NOT NULL mean?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

What is empty string SQL?

A null value in a database really means the lack of a value. It is a special “value” that you can't compare to using the normal operators. You have to use a clause in SQL IS Null. On the other hand, an empty string is an actual value that can be compared to in a database. You simply use two ticks together.


2 Answers

It's been some time, but I'm sure it's a backwards compatibility/legacy back to SQL Server 6.5

SQL Server 6.5 could not store empty string: there was always one space. This changed with SQL 7

So '' -> NULL and ' ' -> '' is correct from an ancient history perspective.

like image 65
gbn Avatar answered Oct 20 '22 00:10

gbn


SELECT ARTICULO as Articulo, 
        case when rtrim(CCOLOR) = '' then null else rtrim(CCOLOR) end as Color, 
        case when rtrim(TALLE) = '' then null else rtrim(TALLE) end as Talle,
from precios

Send null in place of empty.

I find the best solution here:

https://bytes.com/topic/sql-server/answers/143738-bcp-inserting-blank-space-empty-string

I found a work around, using a Case structure in the sql query to change empty string to a null. The BCP in turn outputs the resulting null as an empty! Thanks for your assistance. Eric

like image 32
Diego Palat Avatar answered Oct 20 '22 01:10

Diego Palat