So here is my code block
val cols = df.columns
val w = cols(0)
val query1 = s"select $cols(0), square(age) as age, age as age2, first_name, last_name from test"
val query2 = s"select $w, square(age) as age, age as age2, first_name, last_name from test"
Query 2 works just fine, query 1 throws the following error
no viable alternative at input 'select ['(line 1, pos 7)
== SQL ==
select [Ljava.lang.String;#7988d54(0), square(age) as age, age as age2, first_name, last_name from test
Is there anyway to accomplish query1 without creating a temp variable? I want to acces the indexed cols datatype directly.
You can do it by nesting an expression within the string you're interpolating:
s"select ${col(0)} and then..."
s"select ${df.columns(0)} and then..."
You use the ${expr} to hold some expr which is valid code. The single variable version of the interpolation phrase $foo is actually short hand for ${foo}.
Related
I've been trying to learn how to use sqlite3 for python 3.10 and I can't find any explanation of how I'm supposed to grab saved data From a database and insert it into a variable.
I'm attempting to do that myself in this code but It just prints out
<sqlite3.Cursor object at 0x0000018E3C017AC0>
Anyone know the solution to this?
My code is below
import sqlite3
con = sqlite3.connect('main.db')
cur = con.cursor()
#Create a table called "Datatable" if it does not exist
cur.execute('''CREATE TABLE IF NOT EXISTS datatable
(Name PRIMARY KEY, age, pronouns) ''')
# The key "PRIMARY KEY" after Name disallow's information to be inserted
# Into the table twice in a row.
name = 'TestName'#input("What is your name? : ")
age = 'TestAge'#input("What is your age? : ")
def data_entry():
cur.execute("INSERT INTO datatable (name, age)")
con.commit
name = cur.execute('select name from datatable')
print(name)
Expected result from Print(name) : TestName
Actual result : <sqlite3.Cursor object at 0x00000256A58B7AC0>
The execute statement fills the cur object with data, but then you need to get the data out:
rows = cur.fetchall()
for row in rows:
print(row)
You can read more here: https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/
I am trying to use custom label value in SOQL Query. Query is not accepting custom label value. it is expecting number.
Integer num_days = Integer.valueOf(System.Label.Num_of_Days);
Select id, name FROM contact WHERE LastModifiedDate >= LAST_N_DAYS :num_days
Thanks,
Anil Kumar
The full syntax of the "constant" you're using already has a semicolon in it: LAST_N_DAYS:7 etc. The whole thing has to be a text known at compile time, not just the part before :
This won't even compile, with 1 or 2 semicolons.
Integer x = 7;
List<Account> accs = [SELECT Id FROM Account WHERE CreatedDate = LAST_N_DAYS:x];
System.debug(accs);
You'll need to use dynamic SOQL or use your custom label to construct a date variable
String x = '7';
List<Account> accs = Database.query('SELECT Id FROM Account WHERE CreatedDate = LAST_N_DAYS:' + x);
System.debug(accs);
DateTime cutoff = System.today().addDays(- Integer.valueOf(x));
System.debug(cutoff);
System.debug([SELECT Id FROM Account WHERE CreatedDate <= TODAY AND CreatedDate >= :cutoff]);
Oracle Select query is not returning any results when using trim on char(2) column. The database field has only spaces. However, when the field has a space and a character, I get the correct results.
e.g.
Action_code char(2)
val = " 8"
Select * from abc where trim(Action_code) = trim(val)
Here I get the rows having " 8".
But,
val = " "
Select * from abc where trim(Action_code) = trim(val)
Here I don't get any rows from database where Action_code is " ". But I have such rows in database.
Can someone please help me how to get rows in 2nd case?
I just found that when you trim a variable or database column which has only spaces, it is treated as null by Oracle. So the following query works:
val = " "
Select * from abc where trim(Action_code) is null and trim(val) is null
Now I get the rows from database where Action_code is " ".
Why you don't try to use the nvl function ?
nvl(valueIsNull,returnOtherValue)
?
I want to search for rows whose column email has only the X character.
For example, if the email is XXXX, it should fetch the row but if the email is XXX#XXX.COM it should not be fetched.
I have tried something like this, but it is returning me all emails having the character X in it:
select *
from STUDENTS
where EMAIL like '%[X+]%';
Any idea what is wrong with my query?
Thanks
Try below query:
select *
from STUDENTS
where LEN(EMAIL) > 0 AND LEN(REPLACE(EMAIL,'X','')) = 0;
I would use PATINDEX:
SELECT * FROM STUDENTS WHERE PATINDEX('%[^X]%', Email)=0
Only X means no other characters than X.
To handle NULLs and empty strings you should consider additional conditions. See demo below:
WITH STUDENTS AS
(
SELECT * FROM (VALUES ('XXXX'),('XXX#XXX.COM'),(NULL),('')) T(Email)
)
SELECT *
FROM STUDENTS
WHERE PATINDEX('%[^X]%', Email)=0 AND LEN(Email)>0
This will find all rows where email only contain 1 or more X and no other characters.
SELECT *
FROM STUDENTS
WHERE Email not like '%[^X]%' and Email <> ''
I would like to get all the type names of a user seperated in commas and included in single quotes. The problem I have is that &apos ; character is displayed as output instead of '.
Trial 1
SELECT LISTAGG(TYPE_NAME, ''',''') WITHIN GROUP (ORDER BY TYPE_NAME)
FROM ALL_TYPES
WHERE OWNER = 'USER1';
ORA-01489: result of string concatenation is too long
01489. 00000 - "result of string concatenation is too long"
*Cause: String concatenation result IS more THAN THE maximum SIZE.
*Action: Make sure that the result is less than the maximum size.
Trial 2
SELECT '''' || RTRIM(XMLAGG(XMLELEMENT(E,TYPE_NAME,q'$','$' ).EXTRACT('//text()')
ORDER BY TYPE_NAME).GetClobVal(),q'$','$') AS LIST
FROM ALL_TYPES
WHERE OWNER = 'USER1';
&apos ;TYPE1&apos ;,&apos ;TYPE2&apos ;, ............... ,'TYPE3&apos ;,&apos ;
Trial 3
SELECT
dbms_xmlgen.CONVERT(XMLAGG(XMLELEMENT(E,TYPE_NAME,''',''').EXTRACT('//text()')
ORDER BY TYPE_NAME).GetClobVal())
AS LIST
FROM ALL_TYPES
WHERE OWNER = 'USER1';
TYPE1& ;apos ;,& ;apos ;TYPE2& ;apos ;, ......... ,& ;apos ;TYPE3& ;apos ;,& ;apos ;
I don;t want to call replace function and then make substring as follow
With tbla as (
SELECT REPLACE('''' || RTRIM(XMLAGG(XMLELEMENT(E,TYPE_NAME,q'$','$' ).EXTRACT('//text()')
ORDER BY TYPE_NAME).GetClobVal(),q'$','$'),''',''') AS LIST
FROM ALL_TYPES
WHERE OWNER = 'USER1')
select SUBSTR(list, 1, LENGTH(list) - 2)
from tbla;
Is there any other way ?
use dbms_xmlgen.convert(col, 1) to prevent escaping.
According to Official docs, the second param flag is:
flag
The flag setting; ENTITY_ENCODE (default) for encode, and
ENTITY_DECODE for decode.
ENTITY_DECODE - 1
ENTITY_ENCODE - 0 default
Try this:
select
''''||substr(s, 1, length(s) - 2) list
from (
select
dbms_xmlgen.convert(xmlagg(xmlelement(e,type_name,''',''')
order by type_name).extract('//text()').getclobval(), 1) s
from all_types
where owner = 'USER1'
);
Tested the similar code below with 100000 rows:
with t (s) as (
select level
from dual
connect by level < 100000
)
select
''''||substr(s, 1, length(s) - 2)
from (
select
dbms_xmlgen.convert(xmlagg(XMLELEMENT(E,s,''',''') order by s desc).extract('//text()').getClobVal(), 1) s
from t);