Using variables in a postgres sql block - postgresql

Can you have an SQL block that accepts a variable for input, uses that variable in a join and returns a result set.
The kicker is that I have been asked to do this outside a function - i.e. within an SQL block.
So, for example, I want to pass the value 1234567890 to the variable v_hold:
DO $$
declare
v_hold integer;
BEGIN
select * from t_table_A where ID = v_hold ;
--return alert_mesg;
END$$;
--$$ LANGUAGE plpgsql
The testing I've done says that in order to return a result set, you have to define that in a RETURN TABLE declaration. I've tried to define this outside a function, but I haven't figured it out.
Can this be done outside a function - i.e pass a variable and return a result set based on a select statement which references a variable in the where clause?

You could try using a prepared statement. For example:
PREPARE myStatement (int) AS SELECT * FROM t_table_A where ID = $1;
To then run the statement use the execute command:
EXECUTE myStatement(1234567890);

From the documentation:
DO executes an anonymous code block, or in other words a transient anonymous function in a procedural language.
The code block is treated as though it were the body of a function with no parameters, returning void. It is parsed and executed a single time.
You could generate your code block with a shell script and get the sort of effect you are looking for.

Related

Alias for function or procedure name

I was running into the issue defined in the following article, and the first answer solved my main concern of naming a parameter the same name as a table column. My new concern is that my function/procedure parameters are widely used and the name of my functions/procedures are fairly detailed.
PL/pgSQL column name the same as variable
Is there a way to define an alias for a function or procedure name - to be used inside its body?
Current code:
CREATE OR REPLACE PROCEDURE dbo.PR_DeleteCrazyNamedItemByCrazyNamedID(in NamedID UUID)
LANGUAGE plpgsql AS
$BODY$
DECLARE
BEGIN
Delete from dbo.Table t where PR_DeleteCrazyNamedItemByCrazyNamedID.NamedID = t.NamedID;
...
Desired code:
CREATE OR REPLACE PROCEDURE dbo.PR_DeleteCrazyNamedItemByCrazyNamedID(in NamedID UUID) as proc
LANGUAGE plpgsql AS
$BODY$
DECLARE
BEGIN
Delete from dbo.Table t where proc.NamedID = t.NamedID;
...
Not directly. The function name seems to be visible as record containing input parameters inside the function body, but it is not accessible for an ALIAS as suggested in my referenced answer because it actually serves as outer label. The manual:
Note
There is actually a hidden “outer block” surrounding the body of any
PL/pgSQL function. This block provides the declarations of the
function's parameters (if any), as well as some special variables such
as FOUND (see Section 42.5.5). The outer block is labeled with the
function's name, meaning that parameters and special variables can be
qualified with the function's name.
But you can combine an ALIAS for function parameters with an outer block label (one nesting level below the built-in outer block labeled with the function name) like this:
General example with a function:
CREATE OR REPLACE FUNCTION weird_procedure_name(named_id int)
RETURNS TABLE (referenced_how text, input_value int) LANGUAGE plpgsql AS
$func$
<< proc >> -- outer label!
DECLARE
named_id ALIAS FOR named_id; -- sic!
BEGIN
RETURN QUERY VALUES
('weird_procedure_name.named_id', weird_procedure_name.named_id)
, ('proc.named_id', proc.named_id)
, ('named_id', named_id)
;
END
$func$;
SELECT * FROM weird_procedure_name(666);
referenced_how | input_value
:---------------------------- | ----------:
weird_procedure_name.named_id | 666
proc.named_id | 666
named_id | 666
db<>fiddle here
named_id ALIAS FOR named_id; seems to be pointless noise, but now the input parameter is accessible via block label - effectively doing what you ask for. (You might chose a different name while being at it.)
And I would certainly add a code comment explaining why label and alias are needed, lest the next smart developer should be tempted to remove either.
Applied to your example:
CREATE OR REPLACE PROCEDURE PR_DeleteCrazyNamedItemByCrazyNamedID(in NamedID UUID)
LANGUAGE plpgsql AS
$BODY$
<< proc >> -- !
DECLARE
NamedID ALIAS FOR NamedID; -- sic!
BEGIN
DELETE FROM dbo.tbl t WHERE t.NamedID = proc.NamedID; -- what you wanted !
END
$BODY$;
I would still much rather work with unique parameter names to begin with, so no qualification is required at all. I like to prefix all parameter names with underscore (like: _named_id) - and never do the same for other object names.

Dynamic T-SQL input to T-SQL Task in SSIS

My SSIS package includes a T-SQL task. I have a package parameter that I want to pass into my T-SQL task but I can't find the correct syntax to do this:
DECLARE #myVariable int;
SET #myVariable = $Package::myParameter --not working
SET #myVariable = #[$Package::myParameter] -- also not working
What is the correct way to pass parameters to a T-SQL task?
I'd recommend using an Execute SQL Task as it provides more functionality than an Execute T-SQL Statement Task. However if you're looking to use the T-SQL Task with a parameter this can be done by creating a string variable with an expression that includes the parameter. An example of this is below. To set this as the statement for the T-SQL task, go to the Properties window of the task (press F4), click the ellipsis next to the Expressions field, select the SqlStatementSource property and add the string variable containing the T-SQL as the Expression. Since the variable in your SQL is of the INT data type, I'm assuming the package parameter also is, thus it needs to be cast to a string to be included as part of the expression in the string variable. This will still be parsed as a numeric data type and submitted to SQL Server as such. This casting is done with the (DT_STR, length, code page) function below. This just uses an example length of 10. As a side note, the (DT_WSTR, length) function would be used for Unicode data. Make sure to enclose the SQL text in quotes as done below. Also be aware that parameter names are case sensitive within an expression, for example #[$Package::MyParameter] would return an error if the parameter name was #[$Package::myParameter], starting with a lower case m.
"DECLARE #myVariable INT;
SET #myVariable = " + (DT_STR, 10, 1252)#[$Package::myParameter] + "
UPDATE Database.Schema.Table
SET NAME = 'TW'
WHERE ID = #myVariable"
You can't pass parameters to a T-SQL task.
According to the documentation:
If you need to run parameterized queries, save the query results to
variables, or use property expressions, you should use the Execute SQL
task instead of the Execute T-SQL Statement task. For more
information, see Execute SQL Task.

Conditionally chose the set to iterate over in a FOR LOOP

I would like to know if I can do a if-elsif or case-when inside a loop. No between the for-loop, but as a statament of the foor-loop to choose between a select or another.
something like this:
I have tried with both, if-elsif and case-when....but none of them worked, and I have been lurking around the net to find something but nope.
CREATE OR REPLACE FUNCTION myfunct(op integer, -vars-)
RETURNS table(-vars-)
LANGUAGE plpgsql
AS $function$
DECLARE
selectop record;
-vars-
BEGIN
FOR selectop in (IF (op=1) THEN
SELECT * FROM mytab WHERE somevar=true;
ELSIF (op=2) THEN
SELECT * from mytab WHERE somevar=false;
END IF;)
-things-
RETURN NEXT;
LOOP
---THINGS---
END;
$function$
I wonder why you don't just set a variable and use that in the query. That seems far easier. But from the academic point of view, it's an interesting question.
The problem is that IF or CASE as a control structure don't return something or evaluate to something. So we cannot use them in such a way.
If we think about returning something, then we may think of functions. So you could place a function call there, that returns a different set depending on an argument. But it seems like the function you want to have should implement exactly that, so this would just shift the problem to another level and ultimately ad infinitum.
So let's think about evaluating to something. Expressions come to our mind and indeed there is CASE as an expression, which we could use to switch. The only thing is, at least as far as I know, that cannot handle sets.
But it can handle arrays. So the idea is to use a CASE expression, that evaluates to (two) different arrays.
We will use the fact, that each table also defines a type in Postgres, that is the type of its rows. So we'll iterate over an array of that type.
The next neat thing in Postgres is, that we can use array_agg() to aggregate the complete table or a subset of it into an array. That's how we'll create the arrays we iterate over.
To iterate over the array we'll use a FOREACH loop. (Yes that's not a FOR loop over a cursor but semantically I'd guess that's close enough.)
Such a function could look like the following. elbat is our table and nmuloc4 that column of it we want to compare a value to, depending on the value of the function's argument switch. The function returns a SETOF elbat, that is a set of records from elbat.
CREATE FUNCTION noitcnuf
(switch integer)
RETURNS SETOF elbat
AS
$$
DECLARE
elbat_array elbat[];
elbat_element elbat;
BEGIN
FOREACH elbat_element IN ARRAY(CASE
WHEN switch = 1 THEN
(SELECT array_agg(elbat)
FROM elbat
WHERE nmuloc4 = true)
WHEN switch = 2 THEN
(SELECT array_agg(elbat)
FROM elbat
WHERE nmuloc4 = false)
ELSE
ARRAY[]::elbat[]
END) LOOP
RETURN NEXT elbat_element;
END LOOP;
RETURN;
END;
$$
LANGUAGE plpgsql;
db<>fiddle
In the ELSE branch of the CASE we just have an empty array of the right type. Otherwise we'd receive an error if we pass an argument to the function for which no branch in the CASE exits. Like that, we just get the empty set in such a case.
Note that this would also work for a view or probably even a set returning function instead of a table (I didn't explicitly test the latter).
But I'd also like to warn, that I suspect this approach to be likely less performant than just building up a query depending on variables and do a classic loop over a cursor or at best reduce it to a set based approach with no loops at all.

Postgres function update column ambiguous

I create a postgres function like this:
CREATE OR REPLACE FUNCTION delete_annotation_f(
IN cmtid uuid)
RETURNS bool AS $$
DECLARE
pid uuid;
cmt_cnt int4;
BEGIN
SELECT get_comment_cnt_f(cmtid) INTO cmt_cnt;
UPDATE detail_t SET ann_cmt_cnt=ann_cmt_cnt - cmt_cnt;
RETURN TRUE;
END
$$
LANGUAGE plpgsql;
But when I run this function I get this error:
ERROR: column reference "cmt_cnt" is ambiguous
LINE 1: ...detail_t SET ann_cmt_cnt=ann_cmt_cnt-cmt_cnt WH...
I find this link On Inset: column reference "score" is ambiguous but it could not help me solve the problem. Anyone have solutions?
You are using a variable that have the same name of a column. The query parser could not decide which it must chose, change your variable name then the ambiguity will vanish.
https://www.postgresql.org/docs/current/static/plpgsql-implementation.html
By default, PL/pgSQL will report an error if a name in a SQL statement
could refer to either a variable or a table column. You can fix such a
problem by renaming the variable or column, or by qualifying the
ambiguous reference, or by telling PL/pgSQL which interpretation to
prefer. The simplest solution is to rename the variable or column. A common
coding rule is to use a different naming convention for PL/pgSQL
variables than you use for column names. For example, if you
consistently name function variables v_something while none of your
column names start with v_, no conflicts will occur.
and further:
You can also set the behavior on a function-by-function basis, by
inserting one of these special commands at the start of the function
text:
#variable_conflict error
#variable_conflict use_variable
#variable_conflict use_column

Use custom function with HugSQL

I am using PostgreSQL version 10 on macOS 10.12.6 and would like to use a custom plpgsql function in a query which shall be accessible to HugSQL. The following ansatz works correctly:
-- :name do-something! :! :1
CREATE OR REPLACE FUNCTION helper()
... (function body of helper)
LANGUAGE plpgsql;
INSERT INTO SomeTable (someColumn) VALUES (helper());
This works since HugSQL allows me to write multi-line SQL statements and I can include the function definition of helper().
However, I wonder whether it's actually efficient to do so since now I am redefining the function every time the query do-something! is run. I have tried to put the function definition at the top of the input file, but it only resulted in a compiler exception.
Question: What is the best way to this?
I found a solution. Here it is for the convenience of other users of HugSQL.
The function can be defined in the migrations file that sets up the tables (I use migratus for this purpose). The scope of the function definitions is identical to the scope of the tables, so if the migration reads
CREATE OR REPLACE FUNCTION helper()
... (function body of helper)
LANGUAGE plpqsql;
CREATE TABLE IF NOT EXISTS SomeTable
(...row definitions);
then the function helper() can be used in the query posted above without having to (re-)define it prior to usage:
-- :name do-something! :! :1
INSERT INTO SomeTable (someColumn) VALUES (helper());