i'm trying to create a function GETUSERPROP(prop, filter_prop, filter_value) that selects one item in database filtering by property and value
SET #_GET_PROP = "name";
SET #_FILTER_PROP = "id";
SET #_FILTER_VALUE = "15";
SET #q = CONCAT(
' SELECT ',
#_GET_PROP,
' FROM MYVIEW '
' WHERE 1 ',
' AND (`', #_FILTER_PROP, '` = "', #_FILTER_VALUE, '") '
);
PREPARE stmt FROM #q;
EXECUTE stmt;
the query outside function is running fine, but when I try to put this inside a function, I get the error
mysql dynamic sql is not allowed in stored function or trigger
I need this as a function to use inside other queries, like this:
SELECT
GETUSERPROP("name", "id", "15") AS name,
GETUSERPROP("age", "id", "15") AS age
From error message it is obvious we cannot use dynamic sql in function. Dynamic sql is only possible in procedure. So you have to think in alternative. If number of combination is not too much then you can use IF statement for each possible combination for example.
IF #_GET_PROP = 'name' AND #_FILTER_PROP = 'ID' THEN
SELECT name from MYVIEW where id = #_FILTER_VALUE;
ELSE IF #_GET_PROP = 'Agen' AND #_FILTER_PROP = 'ID' THEN
SELECT name from MYVIEW where id = #_FILTER_VALUE;
................
...............
and so on..
or something like this
SELECT CASE #_GET_PROP WHen 'name' then name when 'id' then ID when 'Age' then Age END from MYVIEW where
((#_FILTER_PROP = 'ID' AND id = #_FILTER_VALUE)
or (#_FILTER_PROP = 'name' AND name = #_FILTER_VALUE)
or (#_FILTER_PROP = 'age' AND age = #_FILTER_VALUE)
) ;
Related
I am doing a procedure to loop over specific field names for 2 reasons:
I want to hash the field name itself using md5 (We are working with data vault);
I want to add each field name value as a row in the table.
I have the following procedure which is working perfect:
CREATE PROCEDURE ADD_OBSERVATION_VALUES()
RETURNS string
LANGUAGE JAVASCRIPT
EXECUTE AS CALLER
AS
$$
arr = [];
var row_num = 1;
// Set the indicators
COLUMN_FIELD_NAMES = ["care_beneficiary", "cg_child_6mo_receiv_ind_iycf_nbr_1st_cons_6mc_iycfc number",
"preg_women_rec_ind_counselling_nbr_1st_cons_pregw_iycfc",
...
];
COLUMN_FIELD_NAMES_TO_HASH = [
"cg_child_6mo_receiv_ind_iycf/nbr_1st_cons_6mc_iycfc",
"cg_child_6mo_receiv_ind_iycf/nbr_followup_2nd_time_6mc_iycfc",
...
];
try{
// while(rows_result.next()){
for (var col_num = 0; col_num<COLUMN_FIELD_NAMES_TO_HASH.length; col_num = col_num+1){
var COL_NAME = COLUMN_FIELD_NAMES_TO_HASH[col_num];
var query = "INSERT INTO LINK_OBSERVATION_FIELD SELECT (SELECT md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))), current_timestamp(), (SELECT 'ONA'), (SELECT (md5(concat(DATE, concat('CAMP', CAMPNO))))), md5(?) FROM IYCF_TEMP";
var stmt = snowflake.createStatement( {sqlText: query, binds:[COL_NAME, COL_NAME]} );
if(stmt.execute()){
// var query = "INSERT INTO SAT_FIELD_VALUES SELECT (SELECT (md5(md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))))), current_timestamp(), NULL, (SELECT 'ONA'), ?, (SELECT 'PENDING'), (SELECT _SUBMISSION_TIME), (SELECT md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))) FROM IYCF_TEMP";
// var stmt = snowflake.createStatement( {sqlText: query, binds: [COL_NAME, COL_NAME, COL_NAME] });
// stmt.execute()
}
}
// }
return "DONE"
}
catch(error){
return error
}
$$;
The first insert query is working fine, when it goes to the second insert query after successful execution, I get the following error:
Numeric value 'care_beneficiary' is not recognized
I am guessing that the error is coming from , ?, of the below insert query:
INSERT INTO SAT_FIELD_VALUES SELECT (SELECT (md5(md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))))), current_timestamp(), NULL, (SELECT 'ONA'), ?, (SELECT 'PENDING'), (SELECT _SUBMISSION_TIME), (SELECT md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))) FROM IYCF_TEMP;
The ? within the CONCATS are working fine, but the standalone field , ?, . In this standalone binded field, I want to get its value from the table not its name, and I am assuming that it is because the field is being read as with quotes, and the query is considering it string that should not be added to a numeric field.
Any idea how to remove quotes or let the query treat it as field name and not as a value?
The solution was as mentioned by Felipe in the comment section of the question, to bind and compose the query with strings and variables:
var query = "SELECT ... " + COL_NAME + "FROM ..."
Apparently IDENTIFIER(COL_NAME) didn't work for me but I am sure that it will work if I knew where to use the binding.
I have created a table with 10 columns in matlab database toolbox. How do i retrieve the values and show them in matlab GUI? when I use the code below, I get Undefined function 'fetch' for input arguments of type 'double' error. Can anybody tell me what is wrong with my code?
f = getappdata(0,'fvalue');
%Set preferences with setdbprefs.
setdbprefs('DataReturnFormat', 'cellarray');
setdbprefs('NullStringRead', 'null');
%Make connection to database.
conn = database('marine_invertebrates', '', '');
%Read data from database.
curs = fetch(conn, sprintf(['SELECT description.commonName'...
' , description.scientificName'...
' , description.kingdom'...
' , description.phylum'...
' , description.subphylum'...
' , description.class'...
' , description.order'...
' , description.family'...
' , description.genus'...
' , description.species'...
' FROM marine_cbir.description WHERE description.imageID = "%s"'], num2str(f)));
curs = fetch(curs);
close(curs);
%Assign data to output variable
results = curs.Data;
commonName = set(handles.edit11,'String');
display (commonName);
scientificName = set(handles.edit1,'String');
display (scientificName);
kingdom = set(handles.edit2,'String');
display (kingdom);
phylum = set(handles.edit3,'String');
display (phylum);
subphylum = set(handles.edit4,'String');
display (subphylum);
class = set(handles.edit5,'String');
display (class);
order = set(handles.edit6,'String');
display (order);
family = set(handles.edit7,'String');
display (family );
genus = set(handles.edit8,'String');
display (genus);
species = set(handles.edit9,'String');
display (species );
My requirement is to fetch value from mysql table by passing column names dynamically which I get from function. But the problem is, it displays it as it is rather then fetching the value of column.
The select query is:
SET #stqry =
CONCAT('SELECT DISTINCT
FD.FormsDataID AS FormDataID,
FC.ColumnName AS FieldName,
IFNULL(FC.CustomDisplayName,FC.ColumnName) AS DisplayName,
GetColumnValue(',_FormID,',FC.ColumnName) AS FieldValue,
GetColumnValue(FC.FormID,FC.ColumnName) AS ColIndex
FROM FormsData FD
LEFT JOIN FormsColumns FC ON FD.FormID = FD.FormID
LEFT JOIN FormsRelationship FR ON FR.FormID = FC.FormID
WHERE FD.FormID = ',_FormID,' AND FD.ID = ',_recordID
,' AND FC.FormID=',_FormID
,' AND FD.PARENT_RECORD_ID = 0 AND FC.IsDisplayInEmail = 1
AND FC.IsActive = 1');
select #stqry;
PREPARE n_StrSQL FROM #stqry;
EXECUTE n_StrSQL;
GetColumnValue()is the function I've made which returns columnname from table.(I need it because columns names are added by user dynamically).
The result I am getting is:
FormDataID FieldName fieldValue
-------------------------------
2497 date_time [1]
2497 auto_email [2]
2497 more_email [3]
But actual result should fetch values of [1],[2],[3] in third column. What am I missing here?Can any one help?
I have a function which takes an argument that is used in where clause
function(string x)-->Now this will create a sql query which gives
select colname from tablename where columnname=x;
Now I want this function to give all rows i.e. query equivalent to
select colname from tablename;
when I pass x="All".
I want to create a generic query that when I pass "All" then it should return me all the rows else filter my result.
Just leave the where condition out.
If you really want it that complicated use
where columnname LIKE '%'
which will only filter nulls.
select colname from tablename
where columnname=(case when #x ="All" then columnname
else #x end)
Try this
select colname from tablename where 1=1
hope the above will work
where 1=1 worked for me, Although where clause was being used all records were selected.
You can also try
[any_column_name]=[column_name_in_LHL]
(LHL=left hand side.)
refer my answer for more details
I had the same issue some time ago and this solution worked for me
select colname from tablename where columnname=x or x = 'ALL'
SELECT * FROM table_name WHERE 1;
SELECT * FROM table_name WHERE 2;
SELECT * FROM table_name WHERE 1 = 1;
SELECT * FROM table_name WHERE true;
Any of the above query will return all records from table.
In Node.js where I had to pass conditions as parameter I used it like this.
const queryoptions = req.query.id!=null?{id : req.query.id } : true;
let query = 'SELECT * FROM table_name WHERE ?';
db.query(query,queryoptions,(err,result)=>{
res.send(result);
}
It's unclear what language you're using for your function, but you have to somehow parse the 'All' prior to getting to sql:
public void query(String param) {
String value = "":
switch (param) {
case 'All':
value = "*";
break;
default:
value = param;
}
String sql = "select colname from tablename where colname="+value;
//make the query
}
If you have to allow 'ALL' to be passed through as the parameter value to your function, then you will need to put some manipulation code in your function to construct your SELECT statement accordingly. I.e. You can detect if the parameter has 'ALL' in it and then omit the WHERE clause from your SQL statement. If a value other than 'ALL' comes through, then you can include the WHERE clause along with the relevant filter value from the parameter.
An example of a piece of code to do this would be;
IF x = 'ALL'
THEN
SELECT COLNAME FROM TABLENAME;
ELSE
SELECT COLNAME FROM TABLENAME WHERE COLUMNNAME = X;
END IF;
Give a conditional check in your code(assuming Java) to append the WHERE clause only when x != 'All'
mySqlQuery = "SELECT colname FROM tablename" +
(x.equals("All") ? "" : "WHERE columnname = "+x);
I have simple query:
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT DATE(date_time) AS day_h
FROM `$table_name`
");
and it is working ok.
But I must do this query with table name and when I try this:
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT `$table_name`.DATE(date_time) AS day_h
FROM `$table_name`
");
or
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query("SELECT v_c_holi_2012.DATE(date_time) AS day_h
FROM `$table_name`
");
this is not working (Fatal error: Call to a member function fetch_assoc() on a non-object).
What I 'm doing wrong?
The date function should not have the table prefix since it is a system function.
Instead you need to put the table alias before your field date($table_name.date_time).
By the way, you don't need to if you select from only one table.
I believe $table_name.DATE(date_time) should be DATE($table_name.date_time)
You should apply the table name to the thing that's in the table (i.e. the field name), not the DATE function (which has nothing to do with your table).
i.e.
$table_name = 'v_c_holi_2012';
$STH_h3 = $DBH_R->query(
"SELECT DATE(`$table_name`.`date_time`) AS `day_h`
FROM `$table_name`"
);