how to use case when to create a new column in table B to show if data from table A also in table B - case

When I try following code it returns attached error code
select acct_key,
(case when acct_key in (
select acct_key
from table_A
)
then 1 else 0 end) as acct_indicator
from table_B;
Executed as Single statement. Failed [804 : 08S01] Socket communication failure for Packet transmit Wed May 25 12:01:18 CDT 2022 socket orig=VTDSSBP.rw.discoverfinancial.com local=/10.2.181.125:61593 remote=VTDSSBPcop2.rw.discoverfinancial.com/170.217.201.43:1025 keepalive=false nodelay=false receive=65536 send=64512 linger=10 traffic=0 concurrent=3 contimeout=10000 conwait=1000 connecttime=38 connecttotaltime=38 connectattempts=1 connectfailures=0 reconnectattempts=0 recoverable=false redrive=false failurecache={} cid=1221d607 sess=106395528 java.net.SocketException: Software caused connection abort: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(Unknown Source) at java.net.SocketOutputStream.write(Unknown Source) at ...

attempt 1:
select a.acct_key,
case when exists (
select acct_key
from table b
where a.acct_key = b.acct_key
)
then 1
else 0
end as acct_indicator
from table a;
failed as
it returns Illegal expression in When Clause of case expression
attempt 2:
select a.acct_key,
case when b.acct_key is not null
then 'yes'
else 'no'
end as acct_ind
from table a
left join table b
on a.acct_key = b.acct_key;
succeed

Related

Simple if else statement is not working in MariaDB

Update:
I want to insert data conditionally
Why this MariaDB query has errors:
if 2 > 1 then
select 'hi'
else
select 'bye'
end if
This is the error:
Error in query (1064): Syntax error near 'else select 'bye' end if' at line 3
if (exists (select * from teachers where name = 'Jennifer'))
then
-- do nothing
else
insert into teachers (name, age)
values ('Jennifer', 30)
end if;
I'm not sure that IF can be used like this outside of a stored procedure or function. You may use the IF() function or a CASE expression instead:
SELECT IF(2 > 1, 'hi', 'bye')
OR
SELECT CASE WHEN 2 > 1 THEN 'hi' ELSE 'bye' END

How can I set query_band for Block Level Compression using Aster's load_to_teradata function,

When you are loading a teradata table in bteq you can set the queryband for block level compression. This even works when you are using querygrid and inserting from a foreign server.
SET QUERY_BAND = 'BlockCompression=Yes;' UPDATE FOR SESSION;
My issue is that I am creating a table on an Aster system and then using the load to teradata function. I suspect there is a syntax call where I can set the query band as part of the load_to_teradata call but after searching the internet and through a reem of teradata documentation I haven't found anything yet.
-- Load Agg data for the YYYYMM to Teradta
SELECT SUM(loaded_row_count),SUM(error_row_count)
FROM load_to_teradata (
ON ( select
Cust_id
, cast(lst_cnf_actvy_dt_tm as date) as lst_cnf_actvy_dt
, cast(sum(str_cnt ) as INTEGER) as acct_open_brnch_use_cnt
, cast(sum(phone_cnt ) as INTEGER) as acct_open_phn_use_cnt
, cast(sum(mail_cnt ) as INTEGER) as acct_open_mail_use_cnt
, cast(sum(onlnchnl_cnt) as INTEGER) as acct_open_onln_use_cnt
, cast(sum(mblbnk_cnt ) as INTEGER) as acct_open_mbl_dvc_use_cnt
, cast(sum(acctopen_cnt) as INTEGER) as acct_open_trck_chnl_cnt
from <someDB>.<someTBL>
where acctopen_cnt > 0
and lower(lst_cnf_actvy_typ_cd) = 'acctopen'
and cast(lst_cnf_actvy_dt_tm as date) between
cast(substring('${YYYYMM}' from 1 for 4) || '-' || substring('${YYYYMM}' from 5 for 2) || '-01' as date) and
cast((cast(substring('${YYYYMM}' from 1 for 4) || '-' || substring('${YYYYMM}' from 5 for 2) || '-01' as date) + interval '1 month') - interval '1 day' as date)
and (str_cnt > 0 or phone_cnt > 0 or mail_cnt > 0 or onlnchnl_cnt > 0 or mblbnk_cnt > 0)
group by 1,2 )
TDPID('TD_RDBMS_C2T') USERNAME('${c2tUID}') PASSWORD('${c2tPWD}') ${LDAP_IND_AST_C2T}
TARGET_TABLE ( 'C2T.t_yyyymm_agg' ) LOG_TABLE ('C2T.t_yyyymm_aggLOG')
MAX_SESSIONS(120));
Was able to get the syntax for the load_to_teradata options. You can see the query_band_sess_info argument after max_sessions and before query_timeout...
load_to_teradata(
ON (source query)
TDPID('tdpid')
TARGET_TABLE('fully-qualified table name')
[ERROR_TABLES('error table'[, 'unique constraint violation table'])]
[LOG_TABLE('table name')]
Teradata QueryGrid: Aster-Teradata Connector
Loading Data From Aster Database to Teradata
Aster Database User Guide for Aster Appliances 301
[USERNAME('username')]
[PASSWORD('password')]
[LOGON_MECHANISM('TD2' | 'LDAP' | 'KRB5')]
[LOGON_DATA('mechanism-specific logon data')]
[ACCOUNT_ID('account-id')]
[TRACE_LEVEL('trace-level')]
[NUM_INSTANCES('instance-count')]
[START_INSTANCE('start-instance')]
[MAX_SESSIONS('max-sessions-number')]
[QUERY_BAND_SESS_INFO('key1=value1;key2=value2;...')]
[QUERY_TIMEOUT('timeout-in-seconds')]
[AUTO_TUNE_INSTANCES('yes'|'no')]
[WORKINGDATABASE(‘dbname’)]
[DIAGNOSTIC_MODE('All'|['GetCOPEntries','CheckConnectivity',
'CheckAuthentication','GetTPTSessions',
'TargetTableOrQuerySchema'])])
);

Errors in triggers

This is my trigger:
CREATE OR REPLACE TRIGGER trg_CheckStaffID
BEFORE INSERT ON ASSIGN
FOR EACH ROW
BEGIN
DECLARE id integer := 0;
SET id := (select count(*) from (select staffid from staff where staffid ='T2');
IF (id=0) THEN
RAISE_APPLICATION_ERROR(-20000,'Please Enter A Valid Staff ID');
END IF;
END;
/
And this is the error message I get:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
( - + case mod new not null
continue avg count current exists max min prior sql stddev
sum variance execute forall merge time timestamp interval
date
pipe
PLS-00103: Encountered the symbol "IF"
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
end not pragma final instantiable order overriding static
member constructor map
Invalid syntax on different places; DECLARE section should be before BEGIN. There's no SET command in PL/SQL.
Here's code that compiles; whether it does what you meant, can't tell. (I'm creating dummy tables, just to make sure that trigger creation wouldn't fail).
SQL> create table assign (id number);
Table created.
SQL> create table staff (staffid varchar2(2));
Table created.
SQL> create or replace trigger trg_checkstaffid
2 before insert on assign
3 for each row
4 declare
5 id integer := 0;
6 begin
7 select count(*)
8 into id
9 from (select staffid
10 from staff
11 where staffid ='T2');
12
13 if id = 0 then
14 raise_application_error(-20000, 'Please Enter A Valid Staff ID');
15 end if;
16 end;
17 /
Trigger created.
SQL>

SQLITE3 return count based on column's value

Example of my table :
ID MACHINE RESULT
1 A fail
2 A pass
3 B pass
4 A fail
The next query gets the number of pass and fail from all the MACHINE
SELECT RESULT, COUNT(*) FROM my_table GROUP BY RESULT
The answer is :
2 fail
2 pass
My goal is to get the pass and fail count from a specific MACHINE .
I tried the follow :
SELECT RESULT, COUNT(*) FROM my_table WHERE MACHINE = 'A' GROUP BY RESULT
It doesnt work as expected .
And I'm expecting :
2 fail
1 pass
Where is my mistake ? :<

oracle function and cursor using dynamic table name

IN my oracle database i want to create a function or procedure with cursor which will use dynamic table name.here is my code.
CREATE OR REPLACE Function Findposition ( model_in IN varchar2,model_id IN number) RETURN number IS cnumber number;
TYPE c1 IS REF CURSOR;
c2 c1;
BEGIN
open c2 FOR 'SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rownumber FROM '||model_in;
FOR employee_rec in c2
LOOP
IF employee_rec.id=model_id then
cnumber :=employee_rec.rownumber;
end if;
END LOOP;
close c2;
RETURN cnumber;
END;
help me to solve this problem.IN
There is no need to declare a c1 type for a weakly typed ref cursor. You can just use the SYS_REFCURSOR type.
You can't mix implicit and explicit cursor calls like this. If you are going to OPEN a cursor, you have to FETCH from it in a loop and you have to CLOSE it. You can't OPEN and CLOSE it but then fetch from it in an implicit cursor loop.
You'll have to declare a variable (or variables) to fetch the data into. I declared a record type and an instance of that record but you could just as easily declare two local variables and FETCH into those variables.
ROWID is a reserved word so I used ROWPOS instead.
Putting that together, you can write something like
SQL> ed
Wrote file afiedt.buf
1 CREATE OR REPLACE Function Findposition (
2 model_in IN varchar2,
3 model_id IN number)
4 RETURN number
5 IS
6 cnumber number;
7 c2 sys_refcursor;
8 type result_rec is record (
9 id number,
10 rowpos number
11 );
12 l_result_rec result_rec;
13 BEGIN
14 open c2 FOR 'SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rowpos FROM '||model_in;
15 loop
16 fetch c2 into l_result_rec;
17 exit when c2%notfound;
18 IF l_result_rec.id=model_id
19 then
20 cnumber :=l_result_rec.rowpos;
21 end if;
22 END LOOP;
23 close c2;
24 RETURN cnumber;
25* END;
SQL> /
Function created.
I believe this returns the result you expect
SQL> create table foo( id number );
Table created.
SQL> insert into foo
2 select level * 2
3 from dual
4 connect by level <= 10;
10 rows created.
SQL> select findposition( 'FOO', 8 )
2 from dual;
FINDPOSITION('FOO',8)
---------------------
4
Note that from an efficiency standpoint, you'd be much better off writing this as a single SQL statement rather than opening a cursor and fetching every row from the table every time. If you are determined to use a cursor, you'd want to exit the cursor when you've found the row you're interested in rather than continuing to fetch every row from the table.
From a code clarity standpoint, many of your variable names and data types seem rather odd. Your parameter names seem poorly chosen-- I would not expect model_in to be the name of the input table, for example. Declaring a cursor named c2 is also problematic since it is very non-descriptive.
You can do this, you don't need loop when you are using dynamic query
CREATE OR REPLACE Function Findposition(model_in IN varchar2,model_id IN number)
RETURN number IS
cnumber number;
TYPE c1 IS REF CURSOR;
c2 c1;
BEGIN
open c2 FOR 'SELECT rownumber
FROM (
SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rownumber
FROM '||model_in || '
) WHERE id = ' || model_id;
FETCH c2 INTO cnumber;
close c2;
return cnumber;
END;

Resources