Creating an SQL Query based on data from an Array
You can approach this by using arrays, in which keys are column name and containing the values
$columns = [
'field1' => 'value1',
'field2' => 'value2',
'field3' => 'value3',
'field4' => 'value4'
];
addSomethingToDB($columns);
function addSomethingToDB($cols){
# Do SQL Injection checks
$query = "INSER INTO `tablename` ( ".implode(",",array_keys($cols))." ) VALUES ( '".implode("','",array_values($cols))."' )";
}
Nested array in a SQL query
what about this? Aggregate twice, first for customer_id, date_time. Then simply for customer_id. (Sorry I've called the date column to date_time)
with input as (
select 123 date_time, 1 customer_id, 'A' article_id
UNION ALL
select 123 date_time, 1 customer_id, 'C' article_id
UNION ALL
select 125 date_time, 1 customer_id, 'B' article_id
UNION ALL
select 124 date_time, 2 customer_id, 'A' article_id
UNION ALL
select 126 date_time, 2 customer_id, 'C' article_id)
select customer_id, array_agg(distinct date_time) date_time, array_agg(STRUCT(article_id)) article_id from (
select customer_id,date_time, array_agg(article_id) article_id from input
group by customer_id, date_time
) group by customer_id
Bigquery : how to declare an array variable and set data with a select statement?
Would you try this one ?
DECLARE my_array ARRAY <STRING>;
SET my_array = ARRAY(
SELECT column_name
FROM my_project.my_dataset.INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'my_table'
);
SELECT my_array;
Or, this will work also.
SET my_array = (
SELECT ARRAY_AGG(column_name)
FROM my_project.my_dataset.INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'my_table'
);
Use SQL query as array parameter (input) in custom function
What you found is an ARRAY constructor, which is not an operator (nor a function), but an SQL construct (an SQL syntax element). The referenced answer used the wrong term (now fixed). The difference might matter.
SELECT * FROM bigger_than_ones(ARRAY(SELECT int_attribute FROM my_table));
You could also use the basic aggregate function array_agg()
, which is easier to integrate in more complex queries - but slower for the simple case:
SELECT * FROM bigger_than_ones((SELECT array_agg(int_attribute) FROM my_table));
Related:
- How to make an array from a SELECT returning more than one row
I assume you are aware of unnest()
? It could be used to radically simplify your test function:
CREATE OR REPLACE FUNCTION bigger_than_ones(input_array int[])
RETURNS SETOF int AS
$func$
SELECT *
FROM unnest(input_array) elem
WHERE elem > 1;
$func$ LANGUAGE sql;
Also, there is often a superior set-based approach to all of this. Constructing an array from a set just to pass it to a function may be unnecessary complication.
Related Topics