How to convert a '' to NULL in postgreSQL - postgresql

I have a postgreSQL table which accepts date in yyyy-mm-dd format and it is not accepting if the incoming date format is ''(no date). There could be some instances when '' gets passed as date. Could anyone help me write a function which checks if the incoming date is '' and then replaces it with NULL and then adds it to the db.

Use nullif()
insert into the_table (the_date_column)
values (nullif(?, ''))
Or for an update
update the_table
set the_date_column = nullif(?, '');

You could use a case expression to check for this. I'm using :arg to represent the inputting string - change it according to the programming language you're using:
INSERT INTO mytable
(my_date_col)
VALUES (CASE LENGTH(:arg) WHEN 0 THEN NULL ELSE TO_DATE(:arg, 'yyyy-mm-dd' END)

Related

Convert ABAP date to HANA date returning NULL if empty

My task is to convert a ABAP style date (i.e. 2017-11-20 which is represented as string "20171120") to a HANA date via sql script. This can easily be done by:
select to_date('20171120','YYYYMMDD') from dummy;
But there is another requirement: if the abap date is initial (value '00000000') the database shall store a null value. I have found a working solution: I replace the potential initial date '00000000' with 'Z' and trim the string to null if only 'Z' is found:
select to_date(trim(leading 'Z' from replace('00000000','00000000','Z')),'YYYYMMDD') from dummy;
-- result: null
select to_date(trim(leading 'Z' from replace('20171120','00000000','Z')),'YYYYMMDD') from dummy;
-- result: 2017-11-20
But this looks like a dirty hack. Has anybody an idea for a more elegant solution?
As explained in my presentation Innovation with SAP HANA - What are my options all that string manipulation is really not necessary.
Instead, use the appropriate conversion functions when dealing with ABAP date and time data. In this case, DATS_TO_DATE is the correct function.
with in_dates as
( select '20171120' as in_date from dummy
union all select '00000000' as in_date from dummy)
select
dats_to_date(in_date)
, in_date
from in_dates;
|DATS_TO_DATE(IN_DATE) |IN_DATE
-------------------------+---------
|2017-11-20 |20171120
|? |00000000
The ? here is the output representation for NULL.
DATS_TO_DATE does not return NULL if the given date is initial (0000-00-00), but a special date value (-1-12-31 to be precise).
To receive a NULL value in this case, as you requested, use the following statement:
NULLIF( DATS_TO_DATE(?), DATS_TO_DATE('00000000'))
e. g.:
INSERT INTO null_test VALUES (NULLIF( DATS_TO_DATE('00000000'), DATS_TO_DATE('00000000')));
=> returns NULL
INSERT INTO null_test VALUES (NULLIF( DATS_TO_DATE('20171224'), DATS_TO_DATE('00000000')));
=> returns 2017-12-24
As there are no tedious string operations involved, this statement should yield good performance.

tsql convert string into date when possible

I've got a column to import into an Azure SQL DB that is supposed to be made of dates only but of course contains errors.
In TSQL I would like to do something like: convert to date if it's possible otherwise null.
Does anyone know a statement to test the convertibility of a string into a date?
use TryCast or Isdate
select
try_Cast('test' as date)
select try_Cast('4' as date)
select case when ISDATE('test')=1 then cast('test' as date) else null end
TryCast will fail if the expression is not in expected format ..ie.,if the explicit conversion of expression is not permitted
select
try_cast( 4 as xml)
select try_Cast(4 as date)
You could use TRY_PARSE:
Returns the result of an expression, translated to the requested data type, or null if the cast fails. Use TRY_PARSE only for converting from string to date/time and number types.
SELECT TRY_PARSE('20129901' AS DATE)
-- NULL
Additionaly you could add culture:
SELECT TRY_PARSE('10/25/2015' AS DATE USING 'en-US')
And importing:
INSERT INTO target_table(date_column, ...)
SELECT TRY_PARSE(date_string_column AS DATE) ...
FROM source_table
...

What is equivalent of isNullOrEmpty in Postgresql select command?

select complaintno from complaintprocess where endtime='';
It Is Not Working
In complaintprocess table endtime datatype is timestamp without time zone.
Here I want to get one of the column in complaintprocess where endtime is empty.
You could not store '' as timestamp. I suspect that by blank you mean NULL value.
SELECT CAST('' AS timestamp);
-- ERROR: invalid input syntax for type timestamp: ""
To filter them you could use:
SELECT complaintno
FROM complaintprocess
WHERE endtime IS NULL;

Update a varchar column depending of the actual value

I'm using PostgreSQL 9.3.
I have a varchar column in a table that can be null and I want to update it depending of its value is null or not.
I didn't manage to do a function that takes a String as argument and updates the value like this:
If the column is null, the function concatenates the current string value, a comma and the string given as argument, else it just adds the string at the end of the current string value (without comma).
So how can I make a different Update depending of the column value to update?
You can use a case statement to conditionally update a column:
update the_table
set the_colum = case
when the column is null then 'foobar'
else the_column||', '||'foobar'
end
An another approach
UPDATE foo
SET bar = COALESCE(NULLIF(concat_ws(', ', NULLIF(bar, ''), NULLIF('a_string', '')), ''), 'a_string')

Return empty string for no match on DateTime

Table [docSVdate]
PK sID, fielID
value DateTime not null
If there is no row for a given PK (sID, fieldID) I need to return an empty string
This is the best I could come up with
Does anyone have something more efficient?
select isnull(convert(varchar,[docSVdate].[value]), '')
from [docSVsys] as [pholder] with (nolock)
left join [docSVdate]
on [docSVdate].[sID] = [pholder].[sID]
and [docSVdate].[fieldID] = 117
where [pholder].[sID] = 6485
If you convert the datetime to a varchar in SQL, you are introducing the language and culture settings of your SQL Server into the date string. You might also be losing precision, depending on exactly what format is being used. And there's potential for error if the application code parses the string differently than SQL produced it.
So the simple answer is - don't do this. Just return it as a datetime. Let the calling application use it directly without converting to a string. Check for null if necessary in the calling application.
If you really want to do this, then there are many techniques that might work, including the join you showed, and the variable the Luis showed in his answer. Here is another technique, which uses a nested query. Perhaps this is what you are looking for:
SELECT ISNULL(
(select convert(varchar, [value])
from [docSVDate]
where [sID] = 6485 and [fieldID] = 117
), '') as [value]
Please be aware that conversion from datetime to varchar involves formatting, whether you like it or not. If you don't specify anything, you get the defaults for whatever system you are running on. For me, running on a database with US English settings, my default format looks like "Jul 21 2013 4:41PM" But if I had different language settings, I might get a completely different result. You should probably pass a format specifier to indicate what format you are looking for. Please reference the Date and Time Styles remarks in the MSDN reference for cast/convert.
if it's just one row...
INNER JOIN?
I'm not sure what the execution plan will show
DECLARE #Value VARCHAR(50)
SET #Value = ''
SELECT #Value = convert(varchar,[docSVdate].[value])
FROM [docSVsys] as [pholder] with (nolock)
INNER JOIN [docSVdate]
ON [docSVdate].[sID] = [pholder].[sID]
AND [docSVdate].[fieldID] = 117
WHERE [pholder].[sID] = 6485
SELECT #Value as Value
Does not need a join at all.
At most one row as the where is the PK,
DECLARE #Value VARCHAR(50)
SET #Value = ''
SELECT #Value = convert(varchar,[docSVdate].[value])
FROM [docSVdate]
WHERE [docSVdate].[sID] = 6485
AND [docSVdate].[fieldID] = 117
SELECT #Value as Value