Postgresql UPDATE syntax error on RAISE exception in CASE / IF condition - sql

I am confused with writing Postgresql UPDATE query with CASE (or IF) condition.
Expected behavior: I have to raise an exception and do not do update if one specific field is not null.
Current behavior: I tries CASE and IF conditions, but every time I got syntax error: SQL Error [42601]: ERROR: syntax error at or near "exception".
Thoughts: maybe there is a way to achieve same result with adding constraint to table?
UPDATE public.SomeTable
SET Title = (
case when EndDate IS null
THEN 'new title'
ELSE raise exception 'Cannot update entity if EndDate is not null'
end),
Description = (
case when EndDate IS null
THEN 'new description'
ELSE raise exception 'Cannot update entity if EndDate is not null'
end)
WHERE Id=4
Version:
PostgreSQL 11.5 (Debian 11.5-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit

The only relatively convenient way I can think to do this uses updatable views:
create view vw_sometable as
select t.*
from sometable t
where endDate is null
with check option;
You would then insert into the view, rather than into the underlying table.
You can further refine this by giving update permissions on the view but not on the underlying table, so all updates need to go through the view.
Well, another method would not return an error, but it would not update the rows. Just include the condition in the where clause:
UPDATE public.SomeTable
SET Title = 'new title',
Description = 'new description'
WHERE Id = 4 AND EndDate is null';
You could add subsequent logic to check if any rows are updated and raise the error there.

remove case after end
UPDATE public.SomeTable
SET Title = (
case when EndDate IS null
THEN 'new title'
ELSE 'Cannot update entity if EndDate is not null'
end ),
Description = (
case when EndDate IS null
THEN 'new description'
ELSE 'Cannot update entity if EndDate is not null'
end )
WHERE Id=4

Related

Add Column to Databricks Table Syntax Error

I am trying to add a column based on a case when statement mapping status to status names. This is in Databricks, and i'm wondering if i'm having an issue with permissions or if my syntax is off somewhere. A similar statement worked in SQL server.
ALTER TABLE dbo.table
ADD status_name as (CASE WHEN status = '0' THEN 'Pink'
WHEN status = '9' THEN 'Green'
WHEN status = '8' THEN 'Blue'
WHEN status = '2' THEN 'Red'
ELSE 'Other'
END);
This is the error message I am getting:
Error in SQL statement: ParseException:
no viable alternative at input 'ALTER TABLE db.table\nADD status_name'(line 2, pos 4)
Anyone know where i'm going wrong here? Shouldn't the syntax be identical between data-bricks and sql server? The table names are different in Databricks.
I noticed that you missed COLUMN in your statement.
ALTER TABLE dbo.table
ADD **COLUMN** status_name

Add column to existing table in SQL with IF/ ELSE Statement

I am suing PgAdmin4
I have a table called Development. This table contains a column called Customer. I want to create a new column called Target which is equal to 1 when the Customer is null and 0 otherwise.
Here is my code:
ALTER TABLE development ADD COLUMN Target INTEGER;
IF Customer IS NULL then
SET Target = 1;
else
SET Target = 0;
END if;
I am getting this error:
ERROR: syntax error at or near "IF"
LINE 3: IF Customer IS NULL then
^
SQL state: 42601
Character: 53
Most databases support generated columns. The syntax is something like this:
alter table development add column int generated always as
(case when customer is null then 1 else 0 end);
The exact syntax varies by database.
This is much more powerful than adding a new column to the table, because a generated column always has the correct value -- even without an update.
You could use an update statement with a case expression:
UPDATE mytable
SET target = CASE WHEN customer IS NULL THEN 1 ELSE 0 END

Store Procedure compiling but value are not getting updated or inserted

I have created below stored procedure in Db2 Server Platform - LUW and version is v10.1.0.6. The stored procedure is getting created absolutely fine.
CREATE OR REPLACE PROCEDURE TAS_TEST
(
IN I_LOGIN_ID VARCHAR(20),
IN I_NAME VARCHAR(100),
IN I_C_NAME VARCHAR(100),
IN I_USER VARCHAR(20),
IN I_DEBUG SMALLINT DEFAULT 0
)
MODIFIES SQL DATA
LANGUAGE SQL
BEGIN
DECLARE V_TOKEN_EXPIRY_DATE TIMESTAMP;
DECLARE V_TOKEN VARCHAR(36);
SET I_LOGIN_ID = TRIM(I_LOGIN_ID);
IF I_LOGIN_ID IS NULL THEN
SIGNAL SQLSTATE VALUE '20000'
SET MESSAGE_TEXT = 'LOGIN ID IS MUST:';
END IF;
IF I_NAME IS NULL THEN
SIGNAL SQLSTATE VALUE '20000'
SET MESSAGE_TEXT = 'NAME IS MUST:';
END IF;
IF I_C_NAME IS NULL THEN
SIGNAL SQLSTATE VALUE '20000'
SET MESSAGE_TEXT = 'C_NAME IS MUST:';
END IF;
IF I_USER IS NULL THEN
SIGNAL SQLSTATE VALUE '20000'
SET MESSAGE_TEXT = 'USER IS MUST:';
END IF;
MERGE INTO TOKEN_DETAILS AS TD
USING(
SELECT
I_LOGIN_ID,
I_TOKEN,
I_NAME,
I_C_NAME,
I_TOKEN_EXPIRY_DATE,
FROM TOKEN_DETAILS
) AS TEMP
ON(TD.I_LOGIN_ID = TEMP.I_LOGIN_ID)
WHEN MATCHED AND TEMP.I_TOKEN IS NOT NULL THEN
UPDATE
SET
I_TOKEN = V_TOKEN,
I_TOKEN_EXPIRY_DATE = V_TOKEN_EXPIRY_DATE
WHEN NOT MATCHED THEN
INSERT INTO TOKEN_DETAILS(
I_LOGIN_ID,
I_TOKEN,
I_NAME,
I_C_NAME,
I_TOKEN_EXPIRY_DATE,
I_CREATED_DATE,
I_CREATED_BY
)VALUES(
I_LOGIN_ID,
V_TOKEN,
I_NAME,
I_C_NAME,
V_TOKEN_EXPIRY_DATE,
CURRENT_TIMESTAMP,
I_USER
);
SELECT I_TOKEN "TOKEN" INTO V_TOKEN FROM TOKEN_DETAILS;
SELECT I_TOKEN_EXPIRY_DATE "TOKEN_EXPIRY_DATE" INTO V_TOKEN_EXPIRY_DATE FROM TOKEN_DETAILS;
END;
GRANT EXECUTE TAS_TEST TO ADMIN;
However, while calling/executing the stored procedure, it's not either updating or inserting the value in the table
CALL TAS_TEST('testuser','service','component','testuser',0);
Can someone please let me know where I might be wrong.
Multiple problems...
You use parameters with the same names as table column names. If you don't qualify them, then you must know the rules used by Db2 to determine, if it's a column or variable or parameter.
References to SQL parameters, SQL variables, and global variables:
Names that are the same should be explicitly qualified. Qualifying a
name clearly indicates whether the name refers to a column, SQL
variable, SQL parameter, row variable field, or global variable. If
the name is not qualified, or qualified but still ambiguous, the
following rules describe whether the name refers to a column, an SQL
variable, an SQL parameter, or a global variable:
If the tables and views specified in an SQL routine body exist at the time the routine is created, the name is first checked as a column name. If not found as a column, it is then checked as an SQL variable in the compound statement, then checked as an SQL parameter, and then, finally, checked as a global variable.
Back to your example, especially the following code:
MERGE INTO TOKEN_DETAILS AS TD
USING(
SELECT
I_LOGIN_ID,
I_TOKEN,
I_NAME,
I_C_NAME,
I_TOKEN_EXPIRY_DATE,
FROM TOKEN_DETAILS
) AS TEMP
ON (TD.I_LOGIN_ID = TEMP.I_LOGIN_ID)
WHEN MATCHED AND TEMP.I_TOKEN IS NOT NULL THEN
UPDATE ...
You merge into the same table and compare every row by the same I_LOGIN_ID table column. Every row of TOKEN_DETAILS has match ON (TD.I_LOGIN_ID = TEMP.I_LOGIN_ID) (unless the table is empty). The UPDATE works only for rows where I_TOKEN column IS NOT NULL setting the value to NULL since V_TOKEN variable is not initialized before MERGE.
Your SELECT INTO statements at the end will fail, if TOKEN_DETAILS contains more than 1 row.

Warning on altering columns in Sybase

I am running the following sql code in sybase
Declare #cp int
select #cp = count(*) from syscolumns where id = object_id('activ') and name = 'pending'
if (#cp = 0 )
begin
execute("
ALTER TABLE activ ADD pending char(1) DEFAULT 'Y'
")
print 'pending added '
end
When I run for the first time I get a "warning: The schema for table activ has changed. Drop and re-create each trigger on this table that uses the if update clause"
On subsequent runs I don't get this warning anymore. Is there any way to avoid getting this warning first time ?
Some helpful links I went through. 1 Information about the error itself. I still have no clue how to remove that error/warning.

Update query if statement for Oracle

I need to update newly created column in my oracle table. To do so I need to use existing values in row to decide how to populate this column, I am getting error:
java.lang.NullPointerException -> See Debug Output for details
This is my query:
UPDATE
SCHEMA_NAME.TABLE_NAME
SET
OCO= IF CO= 'Y' AND COM='Y' THEN
{
'Y'
} ELSE
{
'N'
}
END IF;
Any suggestions on syntax?
You could use CASE expression in the SET clause.
For example,
UPDATE table
SET schema.column = CASE
WHEN CO= 'Y' AND COM='Y' THEN
'Y'
ELSE
'N'
END