Approach: I want to use a date inside the sql() function
Solution: sql(‘DataStore’, 'DELETE FROM table WHERE date_col = [$start_date] ');
Problem with that: is actually multi-fold.
First is the parameter substitution. In all strings DataServices does see, it will check for either [] or {} combinations. Each text inside these brackets will be put into the expression parser and replaced by its value. So the string ‘1+1=[1+1]’ will result in the string ‘1+1=2’. And with {} extra quotes will be put around. Hence in above example, the string
DELETE FROM table WHERE date_col = 2011.12.31
will be sent to the database. And the database will raise an error saying that 2011.12.31 is a weird number it does not understand. So the least we have to do is using {} brackets. Then the string sent to the database will be
DELETE FROM table WHERE date_col = ‘2011.12.31’
If we are lucky, the database does recognize this string as a date, in most cases it will say things like “I expect a date in the format DD/MM/YYYY”. Either way, we do not want to rely on luck, we should define the format.
Note, the to_char is a DataServices function, it is used inside the parameter substitution bracket {} or []. The to_date() function is part of the string sent to the database, so it is a database function. If you use a different database, check the database syntax.
In Oracle for example the way to convert a string to date is by using the to_date() function of Oracle. Note: There is a to_date() function in DS as well, but that one is not used!
sql(‘DataStore’, 'DELETE FROM table WHERE date_col = to_date({$start_date}, ‘YYYY.MM.DD’) ');
Now the database will receive the string
DELETE FROM table WHERE date_col = to_date(‘2011.12.31’, ‘YYYY.MM.DD’)
and hopefully understand what we want.
The last bit is, the {$start_date} forces DataServices to convert a date into a string. As we haven’t specified any format, it will use the internal conversion rules, which use the format YYYY.MM.DD HH24:MI:SS always. And we get a conversion warning. So it would be safer to use the DataServices(!! we are inside the expression!!) to_char() function.
sql(‘DataStore’, 'DELETE FROM table WHERE date_col = to_date( { to_char($start_date, ‘YYYY.MM.DD’)} , ‘YYYY.MM.DD’) ');
Werner Daehn (BOB member since 2004-12-17)