PostgreSQL "?" argument placeholder does not work for "WITH" [duplicate] - sql

This question already has answers here:
Syntax error at end of input in PostgreSQL
(4 answers)
Closed 2 years ago.
I am trying to use ? in the following way (I use it in Golang to generate query, but it seems like it is not Go dependent):
WITH Tmp(name, enabled) AS (
VALUES(?, ?),(?, ?)
)
UPDATE table_groups
SET enabled = (SELECT enabled
FROM Tmp
WHERE table_groups.name=Tmp.name)
WHERE table_groups.name IN (SELECT name FROM Tmp)
getting:
syntax error at or near ","
If I substitute ? in the above statement by concrete values, everything works fine. Is there a problem using ? with WITH and how would I get around it? Thanks.

Go doesn't support this at of the box.
You can use jmoiron/sqlx if you want this functional
example using sqlx (from docs):
var levels = []int{4, 6, 7}
query, args, err := sqlx.In("SELECT * FROM users WHERE level IN (?);", levels)
// sqlx.In returns queries with the `?` bindvar, we can rebind it for our backend
query = db.Rebind(query)
rows, err := db.Query(query, args...)

Related

SqlAlchemy raw SQL queries strange errors [duplicate]

This question already has an answer here:
DB2 error Improper use of a string column, host variable, constant, or function
(1 answer)
Closed 8 months ago.
I´ve been facing some weird issues when studding SQL raw queries using SqlAlchemy.
sqlstr = 'SELECT "City" from CHICAGO_SCHOOLS;'
with engine.connect() as conn:
result = conn.execute(text(sqlstr))
print (result.all())
The query above returns hundreds of "Chicago" as results. So I just tried to get unique results:
sqlstr = 'SELECT DISTINCT "City" from CHICAGO_SCHOOLS;'
with engine.connect() as conn:
result = conn.execute(text(sqlstr))
print (result.all())
Now, all I got is a weird error :
Exception: SQLNumResultCols failed: [IBM][CLI Driver][DB2/LINUXX8664]
SQL0134N Improper use of a string column, host variable, constant, or
function "City". SQLSTATE=42907
At first I thought it was somehow related to the DISTINCT set quantifier. So I tried the same query with another column.
sqlstr = 'SELECT DISTINCT "School ID" from CHICAGO_SCHOOLS;'
with engine.connect() as conn:
result = conn.execute(text(sqlstr))
print (result.all())
And in this query I got all expected results.
I am not being able to truly understand what is wrong!
The issue was related to the column type. It was a CLOB type and that does not allow use of DISTINCT. Thanks to HoneyBadger

Error when trying to create case statement In MS Access [duplicate]

This question already has an answer here:
MS Access Query with CASE statement
(1 answer)
Closed 3 years ago.
Getting Syntax Error( missing operator) in query expression, What am I getting wrong?
SELECT
ExportUF_NEW.Position,
ExportUF_NEW.[User Defined Field 03]
(CASE
WHEN ExportUF_NEW.[User Defined Field 03] = OP THEN "Production"
WHEN ExportUF_NEW.[User Defined Field 03] = STM THEN "Thermal"
ELSE NULL
END) AS OperationGroup
FROM ExportUF_NEW
WHERE (((ExportUF_NEW.[User Defined Field 03]) Is Not Null))
Expect an outcome to new column "OperationGroup" based on ExportUF_NEW[User Defined Field 03].
MS Access did not support CASE WHEN, use switch instead.
Similar link: What is the equivalent of Select Case in Access SQL?

Selecting values from RECORD variable [duplicate]

This question already has answers here:
EXECUTE...USING statement in PL/pgSQL doesn't work with record type?
(2 answers)
Closed 6 years ago.
As part of my k-medoid algorithm, I have declared a record variable called o_random in my function, which I use to store a random row retrieved from a table of crimes as in this query:
EXECUTE 'SELECT * FROM algorithms.kmedoid_crimes_' ||k||' WHERE
cluster_id='||k_count||' OFFSET floor(random()*'||row_count||') LIMIT 1'
INTO o_random;
However, the below query is giving me an error saying "could not identify column "latitude" in record data type". The crimes table I am getting the row from definitely has a field called latitude.. so I'm thinking I'm trying to get the data from the record variable wrongly?
EXECUTE 'UPDATE algorithms.km_cluster_centres_' ||k||'
SET latitude = $1.latitude, longitude = $1.longitude, geom =
ST_Transform(ST_SetSRID(ST_MakePoint($1.longitude, $1.latitude), 4326),3435)
WHERE id=' ||k_count
USING o_random;
Found some solutions on stack but none of them seem to work.. help would be appreciated.
Just a guess
EXECUTE 'UPDATE algorithms.km_cluster_centres_' || quote_literal(k) ||'
SET latitude = ($1).latitude, longitude = ($1).longitude, geom =
ST_Transform(ST_SetSRID(ST_MakePoint(($1).longitude,($1).latitude), 4326),3435)
WHERE id=' || quote_literal( k_count )
USING o_random;
UPDATE: If it dosen't work try to log with http://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html

Fetching SQL data in R with parameters [duplicate]

This question already has answers here:
Pass R variable to RODBC's sqlQuery? [duplicate]
(4 answers)
Closed 7 years ago.
I would like to extract some data from a MySQL server. Therefore Im using the following code:
#connect to database
getPlayersHome <- dbGetQuery(con,"SELECT * FROM match_player_home WHERE match_id = 1;")
This works fine, however I would like include it in a function with a parameter. But if I do this:
getData <- function(selector){
getPlayersHome <- dbGetQuery(con,"SELECT * FROM match_player_home WHERE match_id = selector;")
}
My query does not work (it returns everything). Any thoughts on what goes wrong here?
You are using the selector parameter incorrectly, as you wrote it selector it's interpreted as a literal. You can use sprintf to create the sql string passing parameters:
getData <- function(selector){
sql <- sprintf("SELECT * FROM match_player_home WHERE match_id = %s", selector)
rs = dbSendQuery(con, sql)
}
The string "%s" inside sprintf will be substitute by the value of selector.

PostgreSQL JSON SQL Update Statement

I am testing out how JSON works in PostgreSQL 9.4 and I'm finding it to be really cool so far.
I'm stuck on one part though. I'm hoping it is possible to run a SQL UPDATE statement on JSON data.
What I was trying to see if I could do was have a Nested Set inside JSON data and Update the left and right when I add a comment.
My query is:
UPDATE
comments
SET
comment #>> '{right}' += 2
WHERE
comment #>> '{post_id}' = '{$input['post_id']}'
AND comment#>>'{right}' >= '{$parent->right}'
I do get an error:
Syntax error: 7 ERROR: syntax error at or near "#>>"
LINE 5: comment#>>'{right}' += 2
I've not been able to find a resource that tells me if it's possible to update an item inside the JSON.
Thank you
Updating JSON Data
If the column in your table contains json data and you want to update this data, you can use the following structure:
UPDATE table_name SET column_name = '{"key" : value}'::jsonb
WHERE column_name::jsonb #> '{“new_key” : new_value}'::jsonb;
Note: Usually #> is used as the "contains" operator.