Is it possible to limit the execution of an SQL CRUD-statement with a condition that is completely unrelated to the table it is working on?
E.g. execute the UPDATE only if there is a special date.
UPDATE tabfoo SET name="santa" where id="123" // only if day = 31.12.
I like to have this inside a single statement. I know how to do it inside a script.
Me platform would be MySql or SqLite.
For SQLite you can use the function strftime()
WHERE id = '123'
AND strftime('%d.%m', CURRENT_DATE) = '31.12'
and for MySql the function DATE_FORMAT():
WHERE id = '123'
AND DATE_FORMAT(CURRENT_DATE, '%d.%m') = '31.12'
In MySQL the problem can be solved next way:
UPDATE tabfoo
SET name="santa" WHERE
id="123" AND MONTH(CURDATE()) = 12 AND DAY(CURDATE()) = 31; // only if day = 31.12.
or
UPDATE tabfoo
SET name="santa" WHERE
id="123" AND DATE_FORMAT(CURDATE(), '%d.%m') = '31.12';
For SQLite you can find alternative function
You can try
UPDATE tabfoo SET name="santa" where id="123" and day = 31.12.
otherways you may try a sql stored procedure.
if-else doku
Related
I have to update table which have column data type as integer, but I have an input as a datetime. this is query that i hve writen
UPDATE T_SCH_ETAX_TEMP SET CURRTIME = UNIX_TIMESTAMP
(TIMEDIFF("(SELECT DATE_FORMAT(?,'%H:%i:%s') TIMEONLY)", "(SELECT
DATE_FORMAT(CURRENT_TIMESTAMP,'%H:%i:%s') TIMEONLY)"), LENGTHTIME =
UNIX_TIMESTAMP(TIMEDIFF("(SELECT DATE_FORMAT(?,'%H:%i:%s')
TIMEONLY)", "(SELECT DATE_FORMAT(CURRENT_TIMESTAMP,'%H:%i:%s')
TIMEONLY)")
any one can help how to convert timestamp result as an integer so I can update the table using SSIS
I could be wrong, please forgive me if I am, but you seem to want something simpler:
UPDATE T_SCH_ETAX_TEMP
SET CURRTIME = UNIX_TIMESTAMP(
TIMEDIFF(TIME(?),
TIME(CURRENT_TIMESTAMP))),
LENGTHTIME = UNIX_TIMESTAMP(
TIMEDIFF(TIME(?), TIME(CURRENT_TIMESTAMP)));
Which would only require 2 parameters ('ss');
If this is the case, in can be simplified to:
UPDATE T_SCH_ETAX_TEMP
SET CURRTIME = UNIX_TIMESTAMP(
TIMEDIFF(?,
CURRENT_TIMESTAMP)),
LENGTHTIME = UNIX_TIMESTAMP(
TIMEDIFF(?, CURRENT_TIMESTAMP));
if you pre-format your parameter strings
I am trying to delete 1 month old records from my table using domain.executeUpdate as follows
Bugrerun.executeUpdate("delete Bugrerun b where b.complete = 1 and b.date
< date_sub(curdate(), INTERVAL 1 MONTH) ")
i am trying to use a MySQL date function inside the query.
But this fails with the error
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: 1 near line 1
, column 97
How can we use the My SQL date time functions inside executeUpdate statements
Note that this table has lot of data so fetch and delete individual records will not work
You can try with the below query, just need to validate whether the HQL functions are supported in MySQL dialect:
Bugrerun.executeUpdate("delete Bugrerun b \
where b.complete = 1 \
and month(current_date()) > month(b.date) \
or year(current_date()) > year(b.date)")
You could implement your own Database dialect to include that functionality.
Another option is to do this:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.MONTH, -1);
Bugrerun.executeUpdate("delete Bugrerun b where b.complete = 1 and b.date
< :oneMonthAgo", [oneMonthAgo: cal.time])
Not all mysql functions are available. You can take a look at MySQLDialect that is used by hibernate (and grails) to see the functions you have available for you:
http://grepcode.com/file/repository.springsource.com/org.hibernate/com.springsource.org.hibernate/3.3.1/org/hibernate/dialect/MySQLDialect.java#MySQLDialect
If you want, you can try to use Groovy SQL to execute a SQL statement instead of an HQL statement. If you do that, in your controller or service you should declare a dataSource attribute so you get DataSource injected:
class MyController {
DataSource dataSource
def execSql(){
def sql = new Sql(dataSource)
sql.execute("delete from bugrerun where complete = 1 and date < date_sub(curdate(), INTERVAL 1 MONTH) ")
render "done"
}
}
SELECT
domain_usage.url,
LEFT(url,locate('?',url)) AS cleanURL
FROM
domain_usage
WHERE
MONTH(domain_usage.login_date) = (Now()) AND
YEAR(domain_usage.login_date) = (Now());
Returns no records, and no error ?
im trying to clean the query string from URL field.....
Any thoughts ?
Your date comparisons are wrong. you're basically trying
3 = '2013-01-18 10:36:00'
you need to compare apples to apples:
MONTH(domain_usage.login_date) = MONTH(now())
modify your WHERE condtion,
SELECT domain_usage.url, LEFT(url,locate('?',url)) AS cleanURL
FROM domain_usage
WHERE MONTH(domain_usage.login_date) = MONTH(CURDATE()) AND
YEAR(domain_usage.login_date) = YEAR(CURDATE())
I am using MySQL to make a report showing the number of hours billed for a particular date range and project. The complexity is that the date range is variable for each project (different start month and start day). This information is coming from a value in another database/table.
I have the following UDF in MySQL:
DELIMITER //
CREATE FUNCTION TimeLeft(startday INT, today INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE s INT;
IF startday < today THEN SET s = 0;
ELSE SET s = 1;
END IF;
RETURN s;
END //
DELIMITER;
I use that function in the following query, which is supposed to take the value returned in the TimeLeft function to determine the values for the start month (month(curdate())-#xx) and start day (#yy) for each project to calculate the hours:
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
Here's how I am setting the values for #xx and #yy:
SET #xx = 0; #this is the value that we will use to manipulate the month for the date range
SET #yy = 0;
#yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT #xx:= TimeLeft(#yy,dayofmonth(curdate()));
I am getting some issues:
#yy is not getting the value - possibly my syntax is wrong?
The variables are set at the top of the code, so they are not getting changed for each project as they should be (there should be a different #xx and #yy for each project since each one has a different start and end date).
Here's the full query:
#below is where I assign the variables
SET #xx = 0; #this is the value that we will use to manipulate the month for the date range
SET #yy = 0;
#yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT #xx:= TimeLeft(#yy,dayofmonth(curdate()));
# below is the MySQL query that is meant to use the variables assigned above
SELECT X.expr1 AS 'Project Name', #monthly_hours - SUM(X.expr2) AS 'Hours Billed
FROM
(SELECT
projects.name AS expr1
, sum(time_records.value) AS expr2
FROM project_objects
INNER JOIN projects
ON projects.id = project_objects.project_id
INNER JOIN time_records
ON time_records.parent_id = project_objects.id
WHERE time_records.parent_type = 'Task'
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
AND time_records.record_date <= curdate()
GROUP BY projects.name
UNION
SELECT
projects.name AS expr1
, sum(time_records.value) as expr2
FROM projects
INNER JOIN time_records
ON projects.id = time_records.parent_id
WHERE time_records.parent_type = 'Project'
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
AND time_records.record_date <= curdate()
GROUP BY projects.name) X
GROUP BY X.expr1
I think there is some issue of where I am assigning the variables #xx and #yy. These should be done for each individual Project, so putting them up on the top is probably not the best idea. I'm also not sure if I am assigning the #yy value correctly. It's supposed to query the value of the field of a table that is in another database but it keeps throwing a syntax error on the #yy assignment to that field.
Assign value to #yy inside select:
SELECT #yy:= start_day_of_month FROM dashboard.client;
I need to retrieve data from within a specific date range.Anybody can help me to create a query to getting the information within date range 12-12-2009 to 12-15-2009 from a mysql table.(including 12 and 15)
SELECT * FROM foo WHERE timestamp BETWEEN "2009-12-12" AND "2009-12-15"
Use this function in php first
function ChangeDateforDB($inputdate) {
if($inputdate>0) {
$month = substr($inputdate,0,2);
$date = substr($inputdate,3,2);
$year = substr($inputdate,6,4);
$show = $year."-".$month."-".$date;
return $show;
}
}
After that you can use this in query like this in the checking condition,
checkdate >= '".ChangeDateforDB($fromdate)."' and checkdate <= '".ChangeDateforDB($todate)."'
Check this one, you can get the correct answer.
SELECT ... WHERE DATEDIFF('2009-12-15',yourdatefield) <= 3 ...