How to scrape redirected URL with R - sql

I have afunction
testFun <- function(myTeam){
print(myTeam)
teamResults <- sqlQuery(channel,paste(
"
SELECT soccer.tblResultsallMore.TEAMNAME,
sum(case when soccer.tblResultsallMore.RES='W' then 1 else 0 end) as W,
sum(case when soccer.tblResultsallMore.RES='L' then 1 else 0 end) as L,
sum(case when soccer.tblResultsallMore.RES='D' then 1 else 0 end) as D
FROM soccer.tblResultsallMore
WHERE soccer.tblResultsallMore.TEAMNAME=myTeam
GROUP BY soccer.tblResultsallMore.TEAMNAME
"))
return(teamResults) # no error if this is not returned
}
testFun("Everton")
I f I hardcode 'Everton' in the code, I get the required output
[1] "Everton"
TEAMNAME W L D
1 Everton 1734 1463 1057
but with the parameter there is an error
[1] "Everton"
[1] "42S22 207 [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'myTeam'."
[2] "[RODBC] ERROR: Could not SQLExecDirect
Help much appreciated

In the code you provided the name myTeam is not replaced, it is seen as character string, and the sql statement looks for the team called myTeam.
variabel = "spam"
paste("from table select variabel")
Does not put "spam" in the sql statement inside paste. The correct syntax is:
paste("from table select ", variabel)
In your situation I would use sprintf. An example:
variabel = "spam"
sprintf("from table select %s", variable)
For more detail see the documentation of sprintf.
In regard to your remark, if there is no explicit return statement, the last evaluated expression is returned. For a discussion see:
Explicitly calling return in a function or not

Related

MariaDB's `JSON_LENGTH` - alternative for PostgreSQL

I need to convert some queries written for MariaDB to PostgreSQL syntax. Unfortunately they use the JSON_LENGTH function of MariaDB and im struggling to find an alternative with PostgreSQL.
For clarification:
JSON_LENGTH counts the number of 'entries' on the root level of a JSON object/array in MariaDB:
SELECT
JSON_LENGTH('{"test": 123}') as test1, -- 1
JSON_LENGTH('"123"') as test2, -- 1
JSON_LENGTH('123') as test3, -- 1
JSON_LENGTH('[]') as test4, -- 0
JSON_LENGTH('[123]') as test5, -- 1
JSON_LENGTH('[123, 456]') as test6, -- 2
JSON_LENGTH('[123, {"test": 123}]') as test7; -- 2
Partial solutions in PostgreSQL I came up with:
select
json_array_length('[]'::json) as test1, -- 0
json_array_length('["a"]'::json) as test2, -- 1
length(json_object_keys('{"a": "b"}'::json)) as test3; -- 1
json_array_length is not allowed for JSON objects
json_object_keys is not allowed for JSON arrays
Unfortunately I can't manage to combine the two methods I figured out for PostgreSQL:
I tried to use CASE WHEN:
select
case
when json_typeof('["a"]'::json) = 'array' then json_array_length('["a"]'::json)
when json_typeof('["a"]'::json) = 'object' then length(json_object_keys('["a"]'::json))
else 0
end;
Error:
[0A000] ERROR: set-returning functions are not allowed in CASE
-> json_object_keys is the bad guy here
I tried IF ELSE:
select
IF ('array' = json_typeof('["a"]'::json)) THEN json_array_length('["a"]'::json)
ELEIF (json_typeof('["a"]'::json) = 'object') THEN length(json_object_keys('["a"]'::json))
ELSE 0;
Error:
[42601] ERROR: syntax error at or near "THEN"
I can imagine I have an error in my IF ELSE statement, but I'm unable to figure it out.
Is there any way to replicate MariaDB's JSON_LENGTH behavior with PostgreSQL?
You need to count the number of rows returned by jsonb_object_keys():
This:
with data (input) as (
values
('{"test": 123}'::jsonb),
('"123"'),
('123'),
('[]'),
('[123]'),
('[123, 456]'),
('[123, {"test": 123}]')
)
select input,
case jsonb_typeof(input)
when 'array' then jsonb_array_length(input)
when 'object' then (select count(*) from jsonb_object_keys(input))
when 'string' then 1
else 0
end
from data
returns:
input | case
---------------------+-----
{"test": 123} | 1
"123" | 1
123 | 0
[] | 0
[123] | 1
[123, 456] | 2
[123, {"test": 123}] | 2
Of course this can easily be put into a function:
create or replace function my_json_length(p_input jsonb)
returns int
as
$$
select case jsonb_typeof(p_input)
when 'array' then jsonb_array_length(p_input)
when 'object' then (select count(*) from jsonb_object_keys(p_input))
when 'string' then 1
else 0
end;
$$
language sql
immutable;
I would not name it json_length() to avoid any clashes in case Postgres decides to implement such a function in the future (although I am not aware of such a function in the SQL standard).
Note that jsonb is the recommended data type to store JSON values in Postgres.

Oracle PLSQL using a dynamic variable in a where clause

For testing in Toad, I have the following code
select ...
from ...
where term_code = :termcode AND
(
case
when :theSubject is not null then SUBJ_CODE = :theSubject
else 1 = 1
end
)
AND ptrm_code <> 8
In short: If theSubject is not entered (is null) I want to display all the courses, otherwise I want to display only those where subject_code is the same as the one entered in the variable window in Toad.
But I get an error:
[Error] Execution (77: 68): ORA-00905: missing keyword
in here:
when :theCourse is not null then sect.SSBSECT_SUBJ_CODE = theCourse
You can use boolean logic:
where
term_code = :termcode
and (:theSubject is null or subj_code = :theSubject)

Case in Select Query has syntax error

I want to return a boolean according to a condition on one of the column of my table. I tested it in SQL Server 2014 and it works, but I have no experience in Access.
This is the query I have at the moment, using Access 2007.
SELECT (CASE WHEN Type = 'C' THEN 1 ELSE 0 END) AS EstContrat
FROM Historique_EnTete
Type has the Text type.
I have translated the error message to :
"Syntax error (missing operator) in the expression << (CASE WHEN Type = 'C' THEN 1 ELSE 0 END) >>"
What am I missing?
In access you have IIF
SELECT IIF(Type = 'C', 1, 0 ) AS EstContrat
FROM Historique_EnTete
As Lamak say you also have SWITCH

RODBC "invalid character\n" error when using CASE WHEN statement

I'm attempting to execute a simple "if/then" statement on an Oracle SQL database using RODBC in R. The SQL statement works fine in SQL Developer v4.0.2.15 but throws an error when performing the same statement in R
sqlQuery(channel, "
select
Variable1,
Variable2,
CASE WHEN Variable1 = 0 then 0 else 1 end as Var3
from schema.TABLE
where ROWNUM<100;
"
)
The error message (updated):
[1] "[1] "HY000 936 [Oracle][ODBC][Ora]ORA-00936: missing expression\n"
[2] "[2] ...
The statement works fine when removing the CASE WHEN line, so the error must be in the CASE WHEN syntax.
I've found a semicolon sometimes causes problems in cases like this.
> sqlQuery(con, "select case when dummy = 'X' then 1 else 0 end from dual")
CASEWHENDUMMY='X'THEN1ELSE0END
1 1
> sqlQuery(con, "select case when dummy = 'X' then 1 else 0 end from dual;")
[1] "HY000 911 [Oracle][ODBC][Ora]ORA-00911: invalid character\n"
[2] "[RODBC] ERROR: Could not SQLExecDirect 'select case when dummy = 'X' then 1 else 0 end from dual;'"
> close(con)
If you look at the SQL statement (which seems to appear in it's entirety in the error message), we see:
'\nselect\n UW_NET_ULTIMATE_LOSS_USD,\n UW_NET_WRITTEN_PREMIUM_USD,\n
IF UW_NET_WRITTEN_PREMIUM_USD = 0 THEN testvar=0 ELSE testvar=1 end\n
from bqiread.POLICY_METRICS\nwhere ROWNUM<100;\n
There's no CASE statement here....it apprears to be an IF/THEN/ELSE, which is not valid Oracle syntax.
Perhaps your tool is generating SQL for a different RDBMS than Oracle, and attempting to execute it in Oracle?

Microsoft ODBC Excel Driver Syntax Error (missing operator) in query expression

I am using XL Report Builder version 2.1.4 and trying to execute the following script but, keep getting the error "Microsoft ODBC Excel Driver Syntax Error (missing operator) in query expression".
select Bidders.*
From Bidders
where
If :Param1 = 1 Then
Due > 0 and
Left(Event,2) <> 12
Else
Due = 0 and
Left(Event,2) <> 12
End If
order by
Name
Param1 is a user-entry parameter that can be either "0" or "1".
Does anyone have any advice as to what operator I am missing?
The if in the query looks suspicious. Try writing the query as:
select Bidders.*
From Bidders
where (:Param1 = 1 and Due > 0 and Left(Event,2) <> 12) or
(:Param1 <> 1 and Due = 0 and Left(Event,2) <> 12)
order by Name;
You can simplify this as:
select Bidders.*
From Bidders
where Event not like '12%' and
((:Param1 = 1 and Due > 0) or
(:Param1 <> 1 and Due = 0)
)
order by Name;