Insert NULL values into INT & STRING columns - sql

I need to insert null values ​​in integer and string columns but in the data set that it obtains before obtaining values ​​"---" for the case of string and "NA" for the case of INT, necessary when you have those values ​​are inserted as void I'm using SQL Sever and my query is like that.
INSERT INTO BOEMIC01
(MICRO_DATE, MICRO_YEAR, MICRO_MONTH, MICRO_WEEK, MICRO_DIVISION, MICRO_SUBDIVISION, MICRO_CODE_COUNTRY, MICRO_COUNTRY, MICRO_CODE_CENTER, MICRO_CENTER, MICRO_FREQ, MICRO_TOTAL_M, MICRO_TOTAL_Y, MICRO_TOTAL_Z, MICRO_ID_PROCESS, MICRO_DESC_PROCESS, MICRO_TOTAL_A, MICRO_TOTAL_B, MICRO_TOTAL_C, MICRO_ID_POINT, MICRO_DESC_POINT, MICRO_CODE_MATERIAL, MICRO_DESC_MATERIAL, MICRO_TOTAL_D, MICRO_TOTAL_E, MICRO_TOTAL_F) VALUES
(
'2019-01-15',
'2019',
'1',
'3',
'X',
'Y',
'P001',
'USA',
'USA1',
'USA2',
'Daily',
'2',
'2',
'0',
'158',
'Enva',
'2',
'2',
'0',
'344',
'2',
'---', --NULL
'---', --NULL
'NA', --NULL
'NA', --NULL
'NA' --NULL
)

To insert NULL values use the NULL keyword. As in:
insert into t (col)
values (null);
To insert the default value, which is usually null, just leave the column out of the column list entirely:
insert into t (col1)
values ('happy value');
col2 will be set to its default value -- which is NULL if no other default is defined.
If you are inserting values from another source, then use try_convert() or nullif() For example:
insert into t (col_str, col_int)
values (nullif(#col_str, '---'), try_convert(int, #col_int));

Also, as a matter of standard practice, you should always use query parameters to supply any literal values to your queries, to avoid "SQL injection" issues. For instance, your query would now read:
INSERT INTO BOEMIC01
(MICRO_DATE, MICRO_YEAR, MICRO_MONTH, [...])
VALUES(?, ?, ? [...])
Notice the ? symbols and notice also that they are not in quotes.
Then, when you execute the query, you supply both the SQL string and, separately, an array of values that are to be substituted for each ? in order of occurrence. Now, SQL cannot misinterpret any value as "part of the SQL," because it isn't. Different sets of parameter values can be supplied to the same SQL string each time.
You can use functions such as NULLIF() as mentioned in BJones' comment: NULLIF('---', ?) ... the parameter's value will be passed to the NULLIF function as its second argument. I think that's a fine way to handle your requirement (and it should have been offered as "an answer").

It really depends where the values are coming from, but if for example this insert is inside a Stored Procedure and the values are coming in via parameters then the following shows how to ensure null values for the cases specified. (Irrelevant columns left out for brevity):
INSERT INTO BOEMIC01 (... MICRO_CODE_MATERIAL, MICRO_DESC_MATERIAL, MICRO_TOTAL_D, MICRO_TOTAL_E, MICRO_TOTAL_F)
select ...
, case when #MICRO_CODE_MATERIAL != '---' then #MICRO_CODE_MATERIAL else null end
, case when #MICRO_DESC_MATERIAL != '---' then #MICRO_CODE_MATERIAL else null end
, try_convert(int, #MICRO_TOTAL_D)
, try_convert(int, #MICRO_TOTAL_E)
, try_convert(int, #MICRO_TOTAL_F)
However if you are passing this data from a client application then convert it client side.

Related

How can i use default value on postgres when query include null value

I use Postgres and I've integration app which write data to database. My column should not be null but my app send null value. I tried to set default value but query override this rule with null value. How can i handle this change without code.
My Column configuration looks like this.
If you won't or can't change the query in code, you have to use trigger
If you can change code structure and query:
If the column has a default value, then no need to send NULL value to query
-- Before change
insert into your_table (id, name, default_col) values
(1, 'name', null);
-- After change (remove null data)
insert into your_table (id, name) values
(1, 'name');
Or send default value in insert query
-- Before change
insert into your_table (id, name, default_col) values
(1, 'name', null);
-- After change (Use default keyboard)
insert into your_table (id, name, default_col) values
(1, 'name', default);

Convert 'NULL' to Date in SQL

I have a column in my table called startdate. It is in string format. Most of the fields are 'NULL'. I am copying this column to another table which data type is 'Date'.
How can I convert all the values from string to Date in SQL.
I have tried this code:
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,[startdate],103)
FROM Source_Table
nullif([startdate],'NULL') returns [startdate] unless it equals to 'NULL' and then it returns NULL (a real NULL, not the string 'NULL')
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,nullif([startdate],'NULL'),103)
from Source_Table
For learning purposes, here are some expressions with the same results:
nullif(x,y)
case when x=y then null else x end
case x when y then null else x end
It looks like you are using MSSQL. If you are using MSSQL 2012, the following code should work :
INSERT INTO Destination_Table [new_date]
SELECT IIF([startdate] = "NULL", null, CONVERT(DATE,[startdate],103))
FROM Source_Table
What this does, is use the IIF() method to check the value of [startdate] and if the value is the text "NULL", then return the actual null value which can be allowed in most fields unless you have null disabled on the Destination_Table.[new_date] field.
Since the Date field can only accept and store Date/Time/Date&Time/(actual null) information, the text "NULL" is not valid.
Following is the equivalent for MySQL
INSERT INTO Destination_Table [new_date]
SELECT IF([startdate] == 'NULL', null, CONVERT(DATE,[startdate],103))
FROM Source_Table
(although I am unsure MySQL allows a conversion code as a param to CONVERT() )

Informix Blob data

I need to know if there is any possibility of passing null in blob data using insert statement in Informix.
I know there is an option of LOAD FROM <FILE> INSERT INTO <TABLE>
Which works well, but i am looking for some insert statment, because i am implementing liquibase and i am not finding any way to insert null or leave it in insert values so that it can accept null. This field is set to TRUE for null values.
Error I am getting is following
[Error Code: -617, SQL State: IX000] A blob data type must be supplied within this context.
Tried this
INSERT INTO informix.tti_key_store (id, code, description, value_asc, cts, active)
VALUES
(4, 'EVDSDEALER', 'EVDS Dealer Passphrase', 'nodYzUNAs+htD1Mng3hYYg==', DATETIME (2016-02-17 12:51:34.000) YEAR TO FRACTION(5), 'T')
Tried this
INSERT INTO informix.tti_key_store (id, code, description, value_asc, value_bin, cts, active)
VALUES
(4, 'EVDSDEALER', 'EVDS Dealer Passphrase', 'nodYzUNAs+htD1Mng3hYYg==', NULL, DATETIME (2016-02-17 12:51:34.000) YEAR TO FRACTION(5), 'T')
value_bin is a blob field set to NULL to true.

Oracle: Insert into table(column_list) values(values_list) with some columns defined as default NULL

Suppose you have this Oracle 11g table:
table sample(
mykey int, --primary key
myval varchar2(10 byte) not null,
col1 varchar2(10 byte),
col2 varchar2(10 byte) default NULL)
If you execute this statement from sqldeveloper for example:
insert into sample(mykey, myval) values (1, 'test');
You get
mykey myval col1 col2
1 test null null
Note that it doesn't make a difference for the two nullable columns to specify the 'default null' or not, you'll still have 'null' entered as value for you.
Now, why does the exact same insert from JDBC driver fail with the 'Not enough values' error?
Furthermore, if the column col2 is defined without 'default null', but is still nullable, the JDBC insert works and sets 'null' for both col1 and col2.
Is it just superfluous or plain wrong to specify 'default null' for a column? If Oracle allows me to create the column with that default value and allows me to write SQL code that inserts as in the example correctly, I don't think it's wrong/illegal to do so.
Is this something related to the Oracle DB (or any DB for that matter) or could the application inserting via JDBC driver be issuing a wrong statement?
Thanks in advance
Is it just superfluous or plain wrong to specify 'default null' for a column?
Yes, it superfluous. DEFAULT NULL is implied if you don't specify a default value.
After all that's the only sensible behavior: if you don't provide a value, the only possible choice is to store "unknown" in that column. And that's precisely what NULL means: it is unknown whether there is a value or not.
Now, why does the exact same insert from JDBC driver fail with the 'Not enough values' error?
I don't believe that you are using the exact same statement in your Java program. The "not enough values" error only appears if you - well - don't supply enough values. E.g. by providing less values in the values clause than you have columns in the insert part. The following statement would cause that error:
insert into sample(mykey, myval, col1) values (1, 'test');
I haven't tried, but it could be that something like the following would also cause this error:
PreparedStatement pstmt = connection.prepareStatement("insert into sample(mykey, myval, col1, col2) values (?,?,?,?)");
pstmt.setInt(1, 1),
pstmt.setString(2, 'test');
Note that setXXX() was not called for the third column.
I believe that the JDBC would create an SQL similar to the following:
insert into sample(mykey, myval, col1, col2 ) values (?, ?, ?, ?);
Just to say, i am not into JAVA so the parameters may be written differently.
Having said that, your client expects 4 values and not just 2. It wouldn't know that you may want to only pass a certain set of columns.

SQL Server 2000 - Default Value for varchar fields

I have a sql server nvarchar field with a "Default Value or Binding" of empty string. It also happens to be a not null field.
Does this mean that there is no default or that it is a default of a string with no characters in it.
If I don't insert a value, will it insert with an empty string or fail with a "not null" error?
The default is a blank (empty) string.
If you don't provide a value, the insert will be successful and the value will be blank, not null.
Its the same as (assuming data is the col in question):
create table #t (id int, data varchar(100) not null default(''))
So:
insert into #t (id) values (1)
insert into #t (id,data) values (2,default)
insert into #t (id,data) values (3, 'allowed')
select * from #t
will return
1
2
3 allowed
and ..
insert into #t (id,data) values (1, null)
-- will error
If you have a true empty string as a default, then it will autopopulate with a 0 length string.
You should be careful to ensure it is a 0 length string and not nothing though. If for instance you are looking in the table builder gui for SSMS and it shows a blank for "Default Value or Binding", that means that there is no default value and an insert will fail if it is not populated. If you want it to have a 0 length string, populate it with '' (two single-quotes together with nothing in between.)
Default value for a column is just that - sql server will put that value when you dont supply one for the column. The value in the column will be an empty string. Not null error will not happen