Postgres syntax error in if condition - sql

I am trying to calculate commission and according to that commission value (commiss) i want to update a column value fixed_fee
select st1.* ,(st1.order_item_value * st1.commission_rate)/100 commiss ,
if commiss < 50 then
update payment_error set fixed_fee = -5 where commiss <= 50
else if commiss >= 50 then
update payment_error set fixed_fee = -10 where commiss >=50
else
end if
from payment_error as st1 join payment_error as st2 on st1.order_item_id=st2.order_item_id ;
while running is then error come is :
ERROR: syntax error at or near "<"
LINE 2: if commiss<50 then
^
********** Error **********
ERROR: syntax error at or near "<"
SQL state: 42601
Character: 87

You can't use if in SQL. This is only available in procedural languages like PL/pgSQL.
But more importantly you cannot embed an update statement inside a select statement like that.
What you are trying to do can be done with a single UPDATE statement using a CASE:
update payment_error
set fixed_fee = case
when (order_item_value * commission_rate)/100 <= 50 then -5
else 5 --<<< different value here
end;
You are setting the fixed_fee to -5 in both cases - I assume that is a typo, and you do mean to assign a different fee for the case when the comission is greater than 50

You cannot use update and select together. To update you can try this:
update payment_error
set fixed_fee = case when (order_item_value * commission_rate * .01) < 50 then -5
else 5 --In your case you have use both as -5 so change it as per your reqm

Related

how to use update query in to update query in postgresql

I want to update ChannelInfo what ever Reporting ChannelId update row returns
but this query is not working, giving error:
ERROR: syntax error at or near ""AdsReporting""
LINE : where "CampaignInfo"."id" in (update "AdsReporting" set "adS...
^
SQL state: 42601
Character: 240
can anyone please help me?
Reporting ChannelId is a foreign key relationship with ChannelInfo primary key.
code:
update "ChannelInfo" set "Amount"=CASE WHEN "Duration"='60' THEN "Amount"-12.25 ELSE "Amount"-6.13 END
where "id"=(update "Reporting" set "Status"='run' where "Status"='a' RETURNING "ChannelId");
It sounds like you want to use CTEs:
with u as (
update "Reporting"
set "Status" = 'run'
where "Status" = 'a'
RETURNING "ChannelId"
)
update "ChannelInfo" ci
set "Amount"= (CASE WHEN ci."Duration" = '60' THEN ci."Amount" - uc.cnt * 12.25 ELSE ci."Amount" - uc.cnt * 6.13 END)
from (select "ChannelId", count(*) as cnt
from users u
group by "ChannelId"
) uc
where uc."ChannelId" = ci.id;

Case expression with Boolean from PostgreSQL to SQL Server

I am translating a query from PostgreSQL to SQL Server. I didn't write the query in PostgreSQL and it's quite complicated for my knowledge so i don't understand every piece of it.
From my understand: we are trying to find the max version from p_policy and when insurancestatus = 7 or 14 / transactiontype = CAN, we compare two dates (whose format are BIG INT).
This is the PG Query:
SELECT *
FROM BLABLABLA
WHERE
pol.vnumber = (
SELECT MAX(pol1.vnumber)
FROM p_policy pol1
AND ( CASE WHEN pol1.insurancestatus IN (7,14)
or pol1.transactiontype IN ('CAN')
-- ('CAN','RCA')
THEN pol1.veffectivedate = pol1.vexpirydate
ELSE pol1.veffectivedate <> pol1.vexpirydate
END
)
AND pol1.vrecordstatus NOT IN (30,254)
etc.
I am used to have a where statement where I compare it to a value. I understand here from the Case statement we will have a boolean, but still that must be compared to something?
Anyway the main purpose is to make it work in SQL, but I believe SQL can't read a CASE statement where THEN is a comparison.
This is what I tried:
SELECT *
FROM BLABLABLA
WHERE pol.vnumber =
(
SELECT MAX(pol1.vnumber)
FROM p_policy pol1
WHERE sbuid = 4019
AND ( CASE WHEN pol1.insurancestatus IN (7,14)
or pol1.transactiontype IN ('CAN')
THEN CASE
WHEN pol1.veffectivedate = pol1.vexpirydate THEN 1
WHEN pol1.veffectivedate <> pol1.vexpirydate THEN 0
END
END
)
AND pol1.vrecordstatus NOT IN (30,254)
etc.
And then I get this error from SQL Server (which directly the last line of the current code - so after the double case statement)
Msg 4145, Level 15, State 1, Line 55
An expression of non-boolean type specified in a context where a condition is expected, near 'AND'.
Thank you !Let me know if it is not clear
I think you want boolean logic. The CASE expression would translate as:
(
(
(pol1.insurancestatus IN (7,14) OR pol1.transactiontype = 'CAN')
AND pol1.veffectivedate = pol1.vexpirydate
) OR (
NOT (pol1.insurancestatus IN (7,14) OR pol1.transactiontype = 'CAN')
AND pol1.veffectivedate <> pol1.vexpirydate
)
)
There are 2 main issues with your snippet, SQL Server-syntax-wise.
SELECT * FROM BLABLABLA WHERE
pol.vnumber = /* PROBLEM 1: we haven't defined pol yet; SQL Server has no idea what pol.vnumber is here, so you're going to get an error when you resolve your boolean issue */
(
SELECT MAX(pol1.vnumber)
FROM p_policy pol1
WHERE sbuid = 4019
AND ( CASE WHEN pol1.insurancestatus IN (7,14)
or pol1.transactiontype IN ('CAN')
THEN CASE
WHEN pol1.veffectivedate = pol1.vexpirydate THEN 1
WHEN pol1.veffectivedate <> pol1.vexpirydate THEN 0
END
END
) /* PROBLEM 2: Your case statement returns a 1 or a 0..
which means your WHERE is saying
WHERE sbuid = 4019
AND (1)
AND pol1.vrecordstatus NOT IN (30,254)
SQL Doesn't like that. I think you meant to add a boolean operation using your 1 or 0 after the parenthesis.
like this: */
= 1
AND pol1.vrecordstatus NOT IN (30,254)

How to run procedure without parameter in Teradata

How to run procedure without parameter in Teradata
I'm trying with : call db1.proc_dbOSA()
Error Msg:
Call failed 3707: PROC_DBOSA: Syntax error, expected something
like a name or a Unicode delimited identifier between ‘(‘ and ‘)’
New Procedure with error result.
When i run only code then everything works ok.
REPLACE PROCEDURE db1.proc_dbOSA()
BEGIN
DELETE FROM db1.LOG_dbOSA;
INSERT INTO
db1.LOG_dbOSA
(StoreNo, IDX, Flow, Status, MRP, OSA_IDX, OSA_AC)
WITH a AS (
SELECT
c.StoreCode,
CAST(SUBSTRING(c.ArticleCode FROM 13 FOR 6) AS INT) AS IDX,
RpType,
CASE
WHEN c.MinimumTargetStockWrpl >= l.MinimumTargetStockWrpl THEN CAST(l.MinimumTargetStockWrpl AS INT)
WHEN c.MinimumTargetStockWrpl < l.MinimumTargetStockWrpl THEN CAST(c.MinimumTargetStockWrpl AS INT)
End AS StoreMin,
c.ValUnrestrictedStock
FROM
db1.tab1 c
INNER JOIN
(
SELECT
StoreCode,
ArticleCode,
MinimumTargetStockWrpl
FROM
db1.tab1
WHERE
ProcessingDate = CURRENT_DATE - 14
) l ON c.StoreCode = l.StoreCode AND c.ArticleCode = l.ArticleCode
WHERE
c.ProcessingDate = CURRENT_DATE AND c.MinimumTargetStockWrpl IS NOT NULL AND l.MinimumTargetStockWrpl IS NOT NULL AND l.MinimumTargetStockWrpl > 0
)
, t AS
(
SELECT
CAST(SUBSTRING(ArticleCode FROM 13 FOR 6) AS INT) AS IDX,
RpType,
ArticlesPlanner
FROM
DWH_db_V.STK_B_ARTICLE_DAY_V
WHERE
ProcessingDate = CURRENT_DATE AND StoreCode = 'DR04'
)
SELECT
a.StoreCode,
a.IDX,
t.RpType,
t.ArticlesPlanner,
a.RpType,
CASE
WHEN a.ValUnrestrictedStock > 0 THEN 1
WHEN a.ValUnrestrictedStock <= 0 THEN 0
End AS OSA_IDX,
CASE
WHEN a.ValUnrestrictedStock >= StoreMin THEN 1
WHEN a.ValUnrestrictedStock < StoreMin THEN 0
End AS OSA_AC
FROM
a
LEFT JOIN
t ON t.IDX = a.IDX;
End;
BTEQ Error:
+---------+---------+---------+---------+---------+---------+---------+----
Call proc_dbOSA;
Call proc_dbOSA;
$
* Failure 3707 Syntax error, expected something like '(' between the word
'proc_dbOSA' and ';'.
Statement# 1, Info =18
* Total elapsed time was 1 second.
Call proc_dbOSA();
* Failure 3707 PROC_DBOSA:Syntax error, expected something like a name or
a Unicode delimited identifier between '(' and ')'.
* Total elapsed time was 1 second.
Stored procedures do not support the following:
EXPLAIN and USING request modifiers within a stored procedure
EXECUTE macro statement
WITH clause within a stored procedure.
Stored procedures, as well as macros, do not support the following query logging statements:
BEGIN QUERY LOGGING
END QUERY LOGGING
FLUSH QUERY LOGGING
REPLACE QUERY LOGGING

Percentage of two values returning NULL

Same as yesterdays question which has been answered successfully but different problem. I have two values, 1 and 0 for which I need to calculate the percent change. Based on this website http://www.percent-change.com/index.php?y1=1&y2=0 the percent change between 1 and 0 is -100%. Based on the suggested formula which is (((y2- y1))/ y1) my code looks like this.
DefinedYearVSPriorYearIndividual = ((( CTEDefinedYear.IndividualCases - CTEPreviousYear.IndividualCasesLastYear ))
/ ( CTEPreviousYear.IndividualCasesLastYear ) ) * 100
which returns NULL.
The two numbers are
CTEDefinedYear.IndividualCases = 1
CTEPreviousYear.IndividualCasesLastYear = 0
The desired result should be -100%.
Can anybody see what I'm doing wrong?
Here is the answer.
Declare #y1 as int =1;
Declare #y2 as int =0;
select (((#y2- #y1))/ #y1)*100
Output is -100. You missed the *100 part.
In your case, You switched variables. attached formula is right one.
select ((0 - 1) / 1)*100;
But you used select ((1 - 0) / 0)*100;
so, you will get an error:
Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
You have to handle 0 in the division side, with CASE logic, to avoid divide by zero error.
DECLARE #CTEDefinedYear_IndividualCases INT = 1
DECLARE #CTEPreviousYear_IndividualCasesLastYear INT = 0
SELECT ((#CTEDefinedYear_IndividualCases - #CTEPreviousYear_IndividualCasesLastYear) / (CASE WHEN #CTEPreviousYear_IndividualCasesLastYear = 0 THEN 1 ELSE #CTEPreviousYear_IndividualCasesLastYear END)) * 100
Got it to work with this code.
DefinedYearVSPriorYearIndividual = ISNULL(100.0 *
(ISNULL(CTEDefinedYear.IndividualCases,0)
- ISNULL(CTEPreviousYear.IndividualCasesLastYear,0))
/ NULLIF(CTEPreviousYear.IndividualCasesLastYear,0),0)

Latitude and Longitude conversion error

I'm trying to execute a specific query in my database, but occurs the following error
Table San_Filial
Filial_Id Name lat lon
2 A -19.926131 -43.924373
3 B -19.952192 -43.938789
4 C -19.939626 -43.924541
5 D -19.95529 -43.92953
6 E -19.9099 -43.93124
7 F -19.926191 -43.946067
9 G -19.97125 -43.96622
14 H -19.89038 -43.921734
17 I -19.88838 -43.93059
19 J -19.94305 -43.94093
Query
SELECT *
FROM San_Filial
WHERE San_Filial.Credenciada_Id IN (2,3,4,5,6,7,9,14,17)
AND ACOS(COS(RADIANS(ltrim(San_Filial.lat)))
* COS(RADIANS(convert(float, -19.926131)))
* COS(RADIANS(ltrim(San_Filial.lon))
- RADIANS(convert(float, -43.924373)))
+ SIN(RADIANS(ltrim(San_Filial.lat)))
* SIN(RADIANS(convert(float, -19.926131)))) * 6380 < 5.0
Error
Mesage 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.
Someone can help me ?
Start by seeing if you have any data that is not in a correct format:
select *
from san_filia1
wHERE San_Filial.Credenciada_Id IN (2,3,4,5,6,7,9,14,17) and
(isnumeric(lat) = 0 or isnumeric(long) = 0)
From this, you'll see what is causing the problem and then you can fix it.
The correct fix is probably along these lines:
select *
from (select sf.*,
(case when isnumeric(lat) then cast(lat as float) end) as latf,
(case when isnumeric(long) then cast(long as float) end) as longf
from san_filial sf
) sf
where . . . -- use Latf and Longf instead of lat and long
You need to do the conversion inside a case statement to guarantee that it works as expected. SQL does not guarantee the ordering of statements and a filter might be applied after the calculation.