I want to be able to update the users registration date and modified date if the registered date value is null in the db, otherwise just update the modified date. My current query looks as follows:
WITH notregistered AS (select *
from user
where userid = '1'
AND registrationdate is null)
if (select count from notregistered) < 1 then
UPDATE USER SET name = ?, MODIFIEDDATE = ? WHERE ID = ?;
else
UPDATE MANAGEDUSER SET name = ?, MODIFIEDDATE = ?, REGISTRATIONDATE = ? WHERE ID = ?;
END IF;
However cannot seem to satisfy proper sql syntax. Is there a way to do this within sql or should I put some logic in my server code?
You're missing the parameters for count. Try count(<your_id_column_name>)
to get the count.
As mentioned by @a_horse_with_no_name, you are not able to use IF/THEN statements in that manner. This is achieved through PL/SQL, which in your case would likely be a Procedure. Now I want to preface this with the fact that I'm not highly adept at PL/SQL, but this is what I've came up with that you could give a shot.
It matches very similar to your example, but I've filled the '?' with what I assume is what you want. It should be readable, but the procedure is called with parameters and it does the check that you did in your with statement. That count of columns fills the 'total' variable and the IF/THEN updates based on that result.
Here is the procedure and the command you would do to run it. Experienced people: feel free to suggest improvements as it is a learning aspect for me as well.
CREATE OR REPLACE
PROCEDURE updateUser(
param_name VARCHAR2,
param_modifiedDate DATE,
param_registrationDate DATE,
param_userId NUMBER)
AS
total NUMBER;
BEGIN
SELECT
COUNT(userid)
INTO
total
FROM
USER
WHERE
userid = param_userId
AND registrationdate IS NULL;
IF total = 0 THEN
UPDATE
USER
SET
name = param_name,
modifieddate = param_modifiedDate
WHERE
userid = param_userId;
ELSE
UPDATE
manageduser
SET
name = param_name,
modifieddate = param_modifiedDate,
registrationdate = param_registrationDate
WHERE
userid = param_userId;
END IF;
END;
Execute with:
EXECUTE updateuser('MyName', to_date('2014/07/17', 'yyyy/MM/dd'), to_date('2014/07/17', 'yyyy/MM/dd'), 1234)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.