Error using to_char // to_timestamp - database

I have a database in PostgreSQL and I'm developing an application in PHP using this database.
The problem is that when I execute the following query I get a nice result in phpPgAdmin but in my PHP application I get an error.
The query:
SELECT t.t_name, t.t_firstname
FROM teachers AS t
WHERE t.id_teacher IN (
SELECT id_teacher FROM teacher_course AS tcourse
JOIN course_timetable AS coursetime
ON tcourse.course = coursetime.course
AND to_char(to_timestamp('2010-4-12', 'YYYY-MM-DD'),'FMD') = (coursetime.day +1)
)
AND t.id_teacher NOT IN (
SELECT id_teacher FROM teachers_fill WHERE date = '2010-4-12'
)
ORDER BY t.t_name ASC
And this is the error in PHP
operator does not exist: text = integer (to_timestamp('', 'YYYY-MM-DD'),'FMD') =
(courset... ^ HINT: No operator matches the given name and argument type(s).
You might need to add explicit type casts.
The purpose to solve this error is to use the ORIGINAL query in php with :
$date = "2010"."-".$selected_month."-".$selected_day;
SELECT ...
AND to_char(to_timestamp('$date', 'YYYY-MM-DD'),'FMD') = (coursetime.day +1)
)
AND t.id_teacher NOT IN (
SELECT id_teacher FROM teachers_fill WHERE date = '$date'
)

The error message seems quite clear to me. You are mixing strings and numbers. More precisely, you are converting a string ('2010-4-12') to a timestamp, then to a string, then comparing to an int. This is a type mess, and postgresql is quite strict with typing (for good reasons). What are you trying to do here ?
to_char(to_timestamp('2010-4-12', 'YYYY-MM-DD'),'FMD') = (coursetime.day +1))
Further, you should use a TIMESTAMP, just a DATE.
If (I'm not sure) you are tring to compare the day of week from a date formated as 'YYYY-MM-DD' to a given value (as an integer), you should better use date_part. For example (not tested):
date_part('dow' , to_date('2010-4-12', 'YYYY-MM-DD') ) = coursetime.day + 1

Related

Convert Statement to Crystal Reports SQL Expression

I have a SQL command that works great in SQL Server. Here's the query:
SELECT TOP 1000
(
SELECT COUNT(LINENUM)
FROM OEORDD D1
WHERE D1.ORDUNIQ = OEORDD.ORDUNIQ
)
- (SELECT COUNT(LINENUM)
FROM OEORDD D1
WHERE D1.ORDUNIQ = OEORDD.ORDUNIQ
AND D1.LINENUM > OEORDD.LINENUM)
FROM OEORDD
ORDER BY ORDUNIQ, LINENUM
The query looks at the total lines on an order, then looks at the current "LINENUM" field. With the value of the LINENUM field, it looks to see how many lines have a greater LINENUM value on the order and subtracts it from the number of lines on an order to get the correct Line number.
When I try to add it as a SQL expression in version 14.0.2.364 as follows:
(
(
SELECT COUNT("OEORDD"."LINENUM")
FROM "OEORDD" "D1"
WHERE "D1"."ORDUNIQ" = "OEORDD"."ORDUNIQ"
)
- (SELECT COUNT("OEORDD"."LINENUM")
FROM "OEORDD" "D1"
WHERE "D1"."ORDUNIQ" = "OEORDD"."ORDUNIQ"
AND "D1"."LINENUM" > "OEORDD"."LINENUM"
)
)
I get the error "Column 'SAMDB.dbo.OEORDD.ORDUNIQ' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
If I try to add GROUP BY "OEORDD"."ORDUNIQ" at the end, I get "Incorrect syntax near the keyword 'GROUP'. I've tried adding "FROM OEORDD" at the end of query and it errors out on the word "FROM". I have the correct tables linked in the Database Expert.
EDIT --------------
I was able to get the first query working by getting rid of the alias, it's as follows:
(
SELECT COUNT(LINENUM)
FROM OEORDD
WHERE OEORDH.ORDUNIQ=OEORDD.ORDUNIQ)
)
However, I believe I need to use the alias in the second query to compare line numbers. I'm still stuck on that one.

Update query failed '0' rows affected

I am trying to run this query but the query keeps giving up on me:
Update StockInvoiceInfo set Quantity = Quantity - 2 where p_id = 5 AND ProductDate = convert(Cast('31-5-2015' as datetime)) ;
After Running this code it returns an error below:
Incorrect syntax near '31-5-2015'
The datatype of the ProductDate column isDate. I am using Sql Server 2012.
You have used Convert functions but didn't supplied it with parameters. Also there is no need for this function here. Also take care of date format. I have changed it to standard format:
Update StockInvoiceInfo set Quantity = Quantity - 2
where p_id = 5 AND ProductDate = Cast('2015-05-31' as datetime)
If all you are trying to do is compare a Sql Date, then just use an agnostic format like '20150531' or easier to read '2015-05-31'. No need for casts or convert at all, i.e.
WHERE ... AND ProductDate = '2015-05-31'
However, if ProductDate isn't a date, but one of the *DATETIME* data types, and you are looking to update any time on the same day, then I believe you are looking for something like:
Update StockInvoiceInfo
set Quantity = Quantity - 2
where
p_id = 5
AND CAST(ProductDate AS DATE) = '2015-05-31';
However, the performance will be lousy as the clause isn't likely to be SARGable. You're better off simply doing:
AND ProductDate >= '2015-05-31' AND ProductDate < '2015-06-01';
(Resist the temptation to use between, or hacks like ':23:59:59' as there will be data corner cases which will bite you)
use CAST('5-31-2015' as DATETIME)
with the above update statement you started convert but with incomplete syntax
here the convert syntax
Update StockInvoiceInfo
set Quantity = Quantity - 2
where p_id = 5
AND ProductDate = convert(datetime,Cast('31-5-2015' as varchar),103) ;

convert string date to date type in sql server 2012

In a school website, I want to enable the admin to filter students based on date range when they were born. Dates in my tblStudent are stored as strings, so I cannot use:
SELECT ts.Name from tblStudent ts WHERE ts.BirthDay>'1367/01/31' AND ts.BirthDay<'1377/01/31'
I have saved dates (Jalali Format) in database table tblStudent. I need to do comparison based on dates. So I need to convert date strings to date type in sql server. To this purpose I used:
SELECT convert(date,tblStudent.BirthDay) from tblStudent
However,It stops after 27 results with the following error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I have the following date strings in my tblStudent table.
1379/09/01
1375/04/20
1378/03/02
1378/03/21
1378/04/18
1378/04/18
1378/05/05
1375/04/20
1379/01/03
1378/03/01
1370/09/09
1378/03/22
1375/09/15
1379/09/01
1379/09/10
1375/04/08
1375/05/06
1370/09/09
1379/10/10
1375/04/10
1375/11/01
1375/04/04
1375/08/11
1375/05/05
1376/09/19
1375/12/12
1376/01/13
1375/15/10
1375/04/14
1375/04/04
1375/05/14
1374/11/11
1375/05/30
1375/05/14
1377/12/13
1377/02/31
1377/12/14
1377/01/13
1375/05/31
1377/11/05
1377/07/05
1375/05/31
1377/03/01
1377/04/01
1377/05/02
1377/05/04
1377/03/03
1377/01/14
1377/05/30
1377/04/31
1375/05/30
1376/06/12
1375/12/10
1377/08/14
1377/03/04
1375/04/08
1375/07/18
1375/08/09
1375/09/12
1375/11/12
1376/12/12
1375/01/02
1375/05/09
1375/04/09
1376/01/01
1375/01/30
1377/04/04
1375/05/23
1375/05/01
1377/02/01
1367/12/05
1375/05/31
1373/03/29
1373/03/03
1375/05/05
Is there a way to convert these string dates to date type and then compare them with some query? For example, such a query can be:
SELECT ts.Name from tblStudent ts where ts.BirthDay>'1375/05/31'
I think you can make them ints and compare them:
SELECT ts.Name
FROM tblStudent ts
WHERE CONVERT(INT,REPLACE(ts.BirthDay,'/','') > 13670131
AND CONVERT(INT,REPLACE(ts.BirthDay,'/','') < 13770131
Or for your second example:
SELECT ts.Name
FROM tblStudent ts
WHERE CONVERT(INT,REPLACE(ts.BirthDay,'/','') > 13750531
This would work because having the order Year-Month-Day will ensure that the int representation of a later time will be greater than the int representation of an earlier time.
I really do not know if this is the best idea, but it is an idea of how to do it. After all you would be using a conversion.
From C# you have a few options:
If your input is string:
var dateInt = Int32.Parse(dateString.Replace("/",""));
If your input is Date then:
var dateInt = Int32.Parse(dateValue.ToString("yyyyMMdd"));
You could also pass the string itself in the db and let the db do the work for you :
DECLARE #Date AS VARCHAR(10)
SET #Date = ...--This will be filled with the inputed string
DECLARE #DateINT AS INT
SET #DateINT = CONVERT(INT,REPLACE(#Date,"/",""))

Query with integers not working

I've been searching here on stackoverflow and other sources but not found a solution to this
The query below works as expected expect for when either custinfo.cust_cntct_id or custinfo.cust_corrcntct_id = '' (blank not NULL) then I get no results. Both are integer fields and if both have an integer value then I get results. I still want a value returned for either cntct_email or corrcntct_email even if custinfo.cust_cntct_id or custinfo.cust_corrcntct_id = blank
Can someone help me out in making this work? The database is PostgreSQL.
SELECT
cntct.cntct_email AS cntct_email,
corrcntct.cntct_email AS corrcntct_email
FROM
public.custinfo,
public.invchead,
public.cntct,
public.cntct corrcntct
WHERE
invchead.invchead_cust_id = custinfo.cust_id AND
cntct.cntct_id = custinfo.cust_cntct_id AND
corrcntct.cntct_id = custinfo.cust_corrcntct_id;
PostgreSQL won't actually let you test an integer field for a blank value (unless you're using a truly ancient version - 8.2 or older), so you must be using a query generator that's "helpfully" transforming '' to NULL or a tool that's ignoring errors.
Observe this, on Pg 9.2:
regress=> CREATE TABLE test ( a integer );
CREATE TABLE
regress=> insert into test (a) values (1),(2),(3);
INSERT 0 3
regress=> SELECT a FROM test WHERE a = '';
ERROR: invalid input syntax for integer: ""
LINE 1: SELECT a FROM test WHERE a = '';
If you are attempting to test for = NULL, this is not correct. You must use IS NOT NULL or IS DISTINCT FROM NULL instead. Testing for = NULL always results in NULL, which is treated as false in a WHERE clause.
Example:
regress=> insert into test (a) values (null);
INSERT 0 1
regress=> SELECT a FROM test WHERE a = NULL;
a
---
(0 rows)
regress=> SELECT a FROM test WHERE a IS NULL;
a
---
(1 row)
regress=> SELECT NULL = NULL as wrong, NULL IS NULL AS right;
wrong | right
-------+-------
| t
(1 row)
By the way, you should really be using ANSI JOIN syntax. It's more readable and it's much easier to forget to put a condition in and get a cartesian product by accident. I'd rewrite your query for identical functionality and performance but better readability as:
SELECT
cntct.cntct_email AS cntct_email,
corrcntct.cntct_email AS corrcntct_email
FROM
public.custinfo ci
INNER JOIN public.invchead
ON (invchead.invchead_cust_id = ci.cust_id)
INNER JOIN public.cntct
ON (cntct.cntct_id = ci.cust_cntct_id)
INNER JOIN public.cntct corrcntct
ON (corrcntct.cntct_id = ci.cust_corrcntct_id);
Use of table aliases usually keeps it cleaner; here I've aliased the longer name custinfo to ci for brevity.

How do I search for multiple values in a column where I need to use wildcards?

In SQL Server, I need to search a column for multiple values, but I don't have the exact values, so I need to use wildcards as well.
My current query looks like this:
SELECT *
FROM table
WHERE fieldname in ( '%abc1234%',
'%cde456%',
'%efg8976%')
This doesn't return any results, and yet if I search for any one individual value, I find it, so I know they're in there. Short of doing multiple OR's, which is a bit unwieldy with several hundred values, is there a way to do this?
I'd also be interested to know why this query doesn't work, since the same query without the %'s works just fine (except for the small problem of only catching the few exact matches).
Look at using a Fulltext Index. That should do a much better job with your search, and make your "OR" problem a little nicer to boot:
SELECT *
FROM table
WHERE CONTAINS(fieldname, '"abc1234" OR "cde456" OR "efg8976"')
See also:
http://www.simple-talk.com/sql/learn-sql-server/full-text-indexing-workbench/
The reason the query doesn't work is that it looks for an exact match for fieldname within the list of values in the parens. It doen't do a LIKE comparison where the wildcards are taken into account.
So your query is equivalent to:
SELECT * from table
where fieldname = '%abc1234%' OR
fieldname = '%cde456%' OR
fieldname = '%efg8976%'
Obviously not what you want.
select table.* from (
table join
( select * from values (
( '%abc1234%' ), ( '%cde456%' ), ( '%efg8976%' )
) ) as search( exp ) on 0 = 0
) where fieldname like exp
or perhaps
select table.* from
table join
( select * from values (
( '%abc1234%' ), ( '%cde456%' ), ( '%efg8976%' )
) ) as search( exp )
on fieldname like exp
modulo some syntax I'm sure.
The point being that this comes close to allowing the list of values to be the only parameter.

Resources