Using a string variable as a query SQL statement

I want to construct a custom SQL statement in a string var, then use that var in the cfquery statement.  What is the proper syntax?  Here is my feeble attempt:
  <cffunction ...>
  <cfset var sql_txt="">
        <cfquery name="qSBJs" datasource="cfBAA_odbc">
            "#sql_txt#"
        </cfquery>
    <cfreturn qSBJs>
I've tried using no " or # or just # or just " but nothing works.
what about:
        <cfquery name="qSBJs" datasource="cfBAA_odbc" sql="#sql_txt#">
        </cfquery>
nope.  I wish there was a sql property I could fill *before* the execution of the query.  Any suggestions?

Hi Adam, and/or anyone who may have a few minutes to check this... I got the following code to work.  It calls the getSBJs function from Flash Builder 4.  I get the correct result set back.  Long table names are replaced with short abreviations.  Note that some local vars are declared but not used in the following example. I will use them in the future versions of this same code.  Since I will in the future, like a donkey, mindlessly use this same method for all my queries, it would be much appreciated if I could get a guru to check this code for:
-Pure idiocy
-Mild insanity
-SQL injection vulnerability
-Memory leakage
-Scope dangers
(ignore emoticons, see the underlying text)
    <cffunction name="AbrvTblNms" output="false" returntype="string" >
        <cfargument name="txt" type="string" required="true" />
        <cfset var qAbrvs="">
        <cfset var output_str="#ARGUMENTS.txt#">
        <cfquery name="qAbrvs" datasource="cfBAA_odbc" result="rsltAbrvs">
            SELECT TBL_NM, ABRV FROM BAA_TBL_ABRV ORDER BY 1
        </cfquery>
    <cfloop query="qAbrvs">
            <cfset output_str = Replace(output_str, '[' & qAbrvs.TBL_NM & ']', qAbrvs.ABRV, "ALL")>
    </cfloop>
        <cfreturn output_str>
    </cffunction>
    <!--- Fetch a list photo subjects whose records contain the given search word(s) --->
    <cffunction name="getSBJs" output="false" access="remote" returntype="any" >
        <cfargument name="srch_val" type="string" required="true" />
        <cfset var qSBJs="">
        <cfset var sql_txt="">
        <cfset var whr=""> 
        <cfset var b=False>
        <cfset var in_txt="">
        <cfset var fm_dt="">
        <cfset var to_dt="">
        <cfset var on_dt="">
        <cfset var pht="">
        <cfset var srch_str="">
        <cfset var srch_trm="">
        <!--- Transfer the srch_val to a local variable for further manipulation --->
        <cfset srch_str = "#ARGUMENTS.srch_val#">
        <!---
            An empty search term argument is handled by the BAA FlashBuilder front end.  We test for it again here,
            and substitute a dummy value, in case this function is called by something other than the intended
            FlashBuilder front end, and that front end doesn't protect us from an empty search term argument.
            Remember that we must still "hand back" a valid query structure to avoid causing a data type error
            in the calling function, so we search for a dummy value that will allow the query to proceed but is
            guaranteed to return an empty result set.  If the srch_val argument is not empty, transfer the value of
            the srch_str local variable to the srch_trm local variable.
        --->
        <cfif Not (Len(srch_str))>
            <cfset srch_str = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
        </cfif>
        <cfset srch_trm = "#srch_str#">
        <cfset sql_txt =
            "SELECT DISTINCT
              [BAA_SBJ].SRC_SYS_NM, [BAA_SBJ].SRC_SYS_GUID, [BAA_SBJ].OBJ_GUID, [BAA_SBJ].SBJ_NM, [BAA_SBJ].SBJ_DOB, [BAA_SBJ].SBJ_ID, [BAA_SBJ].NOTE, [BAA_SBJ].CDT, [BAA_SBJ].CTM, [BAA_SBJ].CBY, [BAA_SBJ].MDT, [BAA_SBJ].MTM, [BAA_SBJ].MBY
            FROM
              BAA_SBJ [BAA_SBJ]
              LEFT JOIN BAA_SES [BAA_SES] ON [BAA_SES].PAR_GUID = [BAA_SBJ].OBJ_GUID
              LEFT JOIN BAA_IMG [BAA_IMG] ON [BAA_IMG].PAR_GUID = [BAA_SES].OBJ_GUID
            WHERE [WHERE_CLAUSE] ORDER BY [BAA_SBJ].SBJ_NM">
        <cfset whr = "([BAA_SBJ].SBJ_NM CONTAINING TRIM( rm_srch_trm1 ) OR " &
                "[BAA_SBJ].NOTE CONTAINING TRIM(:prm_srch_trm2 ) OR " &
                "[BAA_SBJ].SBJ_DOB CONTAINING TRIM(:prm_srch_trm3 ) OR " &
                "[BAA_SES].SES_TYP CONTAINING TRIM(:prm_srch_trm4 ) OR " &
                "[BAA_SES].NOTE CONTAINING TRIM(:prm_srch_trm5 ) OR " &
                "[BAA_IMG].NOTE CONTAINING TRIM(:prm_srch_trm6 ))">
        <cfset sql_txt = Replace(sql_txt,"[WHERE_CLAUSE]", "#whr#", "ALL")>
        <cfset sql_txt = AbrvTblNms(sql_txt)>
    <!--- Through experimentation, I learned that each occurance of a param must be uniquely named.
              It would be very handy, if the param value was applied to *all* occurances of the param.
                    That way, I could get away with using one .addParam line instead of 6 --->
        <cfscript>
        queryService = new query();
        queryService.setDatasource("cfBAA_odbc");
        queryService.setName("qSBJs");
        queryService.setAttributes(sql="#sql_txt#");
        queryService.addParam(name="prm_srch_trm1", value="#srch_trm#", cfsqltype="VARCHAR");
        queryService.addParam(name="prm_srch_trm2", value="#srch_trm#", cfsqltype="VARCHAR");
        queryService.addParam(name="prm_srch_trm3", value="#srch_trm#", cfsqltype="VARCHAR");
        queryService.addParam(name="prm_srch_trm4", value="#srch_trm#", cfsqltype="VARCHAR");
        queryService.addParam(name="prm_srch_trm5", value="#srch_trm#", cfsqltype="VARCHAR");
        queryService.addParam(name="prm_srch_trm6", value="#srch_trm#", cfsqltype="VARCHAR");
        result = queryService.execute();
        qSBJs = result.getResult();
        </cfscript>       
        <!--- <cfquery name="qSBJs" datasource="cfBAA_odbc">
        </cffunction>
        </cfquery> --->
        <cfreturn qSBJs>
    </cffunction>
THANKS TO ADAM AND DAN FOR HELPIMG ME GET THIS FAR!  Now, don't let me embarass you by doing something dum and giving you "credit", if you see me doing something dum above.  Thanks!

Similar Messages

  • Can I use a OID rule for a Query SQL Lov of BIP?

    Hi. Can I use OID data (rules) for a query sql lov in BIP? Ex. filters users/store.
    Thank you.
    R.

    Hi,
    I didn't look at the example, but if you want to secure your application then you should use container managed security. Read this .
    Anyway, you could add this before return "good"; in your login_action()
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", user);Then, you can access this from anywhere in the application by using #{sessionScope.username}.
    Pedja

  • How to set Query SQL Statement parameter dynamically in Sender JDBCAdpter

    Hi All,
    I have one scenario in which we are using JDBC Sender Adapter.
    Now in this case,we need to set Query SQL Statement with a SELECT statement based on some fields.
    This SQL statement is not constant, it would need to be changed.
    Means sometimes receiver will want to execute SQL statement with these fields and sometimes they will want to execute it with different fields.
    We can create separate channels for each SQL statement but again that is not an optimum solution.
    So ,I am looking out for a way to set these parameters dynamically or set SQL statement at Runtime.
    Can you all please help me to get this?

    Shweta ,
    <i>Sometimes receiver will want to execute SQL statement dynamically</i>....
    How you will get the query dynamically? Ok Let me assume, consider they are sending the query through file, then its definitely possible. But u need BPM and also not sender JDBC receiver adapter instead, receiver JDBC adapter.
    SQL Query File ->BPM>Synchronous send [Fetch data from DB]--->Response -
    >...............
    Do u think the above design will suit's ur case!!!!
    Best regards,
    raj.

  • Query SQL Statement & Update SQL Statement

    Hi!
    I configure the JDBC adapter sender (XI) to take data from MSSQL database.
    I have to run select like this:
    SELECT
    tblMilestone.Site,
    tblMilestone.Revision,
    tblMilestone.MilestoneNameID,
    tblMilestone.ApprovedDate,
    tblMilestoneName.MilestoneName
    FROM
    tblMilestoneName
    INNER JOIN tblMilestone ON tblMilestoneName.MilestoneNameID = tblMilestone.MilestoneNameID
    WHERE tblMilestone.StatusCode = 1;
    My question is what "Update SQL Statement" I should use in communication channel definition? I only need to update tblMilestone or this two tables?
    Maybe you give me some example.

    Check this from SAP help...
    Update SQL Statement
    You have the following options:
    &#9679;     Enter a valid SQL statement that is to be applied to the database once the data (determined from the Query SQL Statement) has been successfully sent to the Integration Server/PCK.
    It must be an INSERT, UPDATE, or DELETE statement.
    &#9679;     In place of the SQL statement, you can also enter <TEST>. Once the data determined from Query SQL Statement has been successfully sent, the data in the database remains unaltered.
    This is recommended if the data has not only been read, but also changed by a stored procedure entered under Query SQL Statement.

  • Xi JDBC Adapter - Query SQL Statement & Update SQL Statement

    Hi!
    I configure the JDBC adapter sender (XI) to take data from Oracle database.
    I set the Query and Update SQL Statement in the Processing parameters of the communication channel in this way:
    Query SQL Statement :
    SELECT * FROM XI_TABLE WHERE STATUS = 'WAIT' ORDER BY ROW_NUM
    Update SQL Statement :
    UPDATE XI_TABLE SET STATUS = 'DONE', DATE = SYSDATE WHERE STATUS = 'WAIT'
    My question is :
    If a new record with the field STATUS = 'WAIT' is added to the table (xi_table) during the time between the execution of the query statement and the start of the update statement, what will happen to that record during the update?
    There is a way to avoid the update of that record? or to pass to the update statement only the record selected in the query statement?
    Please, may you give me some example?
    Thanks,
    Francesco

    hi,
    did you check "Isolation Level for Transaction"
    for the sender jdbc adapter?
    http://help.sap.com/saphelp_nw04/helpdata/en/7e/5df96381ec72468a00815dd80f8b63/content.htm
    Regards,
    michal

  • Using collections / Bind variables with a PL/SQL functio returning a query

    I have this code, which is supposed to assign collection variables as column names
    FOR i in 1 .. Collection_count -1
    LOOP
    SELECT c002 into :P341_M1 FROM APEX_collections WHERE collection_name = 'MA_SKILLS' AND seq_id=i;
    SELECT c002 into varholder FROM APEX_collections WHERE collection_name = 'MA_SKILLS' AND seq_id=i;
    vQuery:= vQuery || 'SUM(decode(label, ''Aware'', product_'|| i || ', ''Expert'', product_' || i || ', ''Proficient'', product_' || i || ', ''Advanced(Demo)'', product_' || i || ' )) as ';
    vQuery:=vQuery || varholder || ', ' ;
    END LOOP;
    I've tried &P341_M1. , :P341_M1, ':P341_M1', varholder
    When I try '&P341_M1' it returns the whole SUM(decode... line as the label
    Basically Im having a hard time using bind variables with the PL/SQL returning a query...anybody?

    Ok so working through this problem more I have realized that the problem is using the for loop i as an index value
    This will get a value:
    SELECT c002 into :P341_M1 FROM APEX_collections WHERE collection_name = 'MA_SKILLS' AND seq_id=2;
    But this won't
    SELECT c002 into :P341_M1 FROM APEX_collections WHERE collection_name = 'MA_SKILLS' AND seq_id=i;
    I'm in the for loop, and use the i variable in other places within this loop...Is there a reason why I can't compare seq_id to i?
    My new code as follows:
    FOR i in 1 .. Collection_count -1 --apex_application.g_f01.COUNT - 1
    LOOP
    varholder:=i;
    SELECT c002 into :P341_M1 FROM APEX_collections WHERE collection_name = 'MA_SKILLS' AND seq_id=2;
    SELECT c002 into varholder FROM APEX_collections WHERE collection_name = 'MA_SKILLS' AND seq_id=4;
    vQuery:= vQuery || 'SUM(decode(label, ''Aware'', product_'|| i || ', ''Expert'', product_' || i || ', ''Proficient'', product_' || i || ', ''Advanced(Demo)'', product_' || i || ' )) as f';
    vQuery:=vQuery || :P341_M1 ||i||', ' ;
    END LOOP;

  • Setting Prompt Directory path using a string variable?

    So when you define a Prompt you get the form P[promptname.wav] and all is good.  What we want to do is have that prompt name be retrieved from a prompt directory which is defined by a string.   So assume all your prompts have the same numbers like 1001.wav but the actual file is customized based on things like Sales/1001.wav and Marketing/1001.wav   and you want to have a StringValue DirectoryName set the Directory to Sales or Marketing.   The Script does not seem to support setting P["DirectoryName"/1001.wav] where Directory Name is a string variable.    Is there a solution to this other than changing the entire prompt to a string type and dropping the P[] data type entirely?   

    I am working with a similar issue.   It is simple enought to set the Prompt Directory but when it is a variable it seems to have different results.  The attached simple script is used to demonstrate Sam's recommendation.  The XML document is embedded in the script variable, so you dont need to create it.   So the script reaches into the XML document and pulls up the variable strDirectoryName and then adds "/" to it and then sets the strPromptDirectory.   I have done it three ways:  Hard coded, string value for prompt' and prompt data type resolved from string.  As you single step through the script you will find that all values populate appropriately, but only the hard coded play prompt actually plays the prompt.  The other two assemblies fail.  (Clearly it assumes the prompt 10001.wav is in the directory Generic/ if you want to try it).    Written in  Version 8.5 editor.  

  • Using a string variable to create an object

    Hi, I just have a quick question. It is probably very simple but I can not seem to find an asnwer anywhere.
    I have a class called Receive, from this class I derrive 12 difference other classes.
    I also have a hashtable with a bunch of Object objects. At run time I get one of these objects according to some hastable key. So once I have this object I need to cast it to the right type (one of the above mentioned 12).
    So I know I can find out which type this object is by doing this: object.getClass()
    This returns a Class object. I then need to somehow use this class object to perform the cast. I tried everything and it doesnt seem to work. Then I thought well I can get the string name of the class : object.getClass().getName()
    So I'm wandering if there is a way to use this string to cast my object. Or maybe there is another way.
    I did see the cast() method in the Class api but I can't figure out the point of it since is returns an Object class object and not my class's object.

    I took your advice and re factored the Receive class so it had all the functionality I needed except two methods which would then be overridden in the derived classes. What I had a hard time understanding is once an object of class say SpecialReceive extends Receive it can be referred to as Receive yet still maintain that it's a SpecialReceive.
    What I mean is if I give a Receive object to some method and this method has no idea that this object is actually SpecialReceive and it calls a method say run() which gets overridden by the SpecialReceive. I thought that since this method has no idea what type of Receive this object is it will execute Receive's run(). But it actually does know what type of class it is and it executes the right run() method (the one that SpecialReceive overrides).
    After I realized this there is no more need for casting.
    Thanks everyone for your contributions.

  • How to use reference parameters (BAPI Import Parameters) in SQL statements

    Dear SAP gurus
    I have a question on using parameters passed in a custom BAPI in SQL statements.
    I am sending 2 parameters  TABLENAME, COLUMNNAME into a custom bapi.
    In the BAPI I need to give an sql command some thing like
    select * from TABLENAME where COLUMNNAME = '100'.
    Where TABLENAME and COLUMNAME may vary depend on what parameters are sent while calling this BAPI.
    Even defining an internal table that has the structure of TABLENAME is not working.
    I used the following statement 'data: ls_TABLENAME type TABLENAME', which generates error message saying TABLENAME is unknons.
    Any feedback will be highly appreciated.
    Thanks
    Ram

    As far as I know you can not give parameter to a select query like that. You should describe the tablename and the columnname as string type.  Then assign the values to them you want to use in query.
    data: str_table type string.
    data: str_column type string.
    select * from  (str_table)  into  <g_t_table>  where (str_column)  = '100'.
    If the table name is not determined until runtime, you must specify an output area with INTO .

  • How to pass the bind variable value to the sql statement of the LOV

    Hi,
    I am using Forms 10g builder.
    I have a text item which will be populated by a LOV when i press a button, but i have a bind variable in the SQL statement of the LOV. That bind variable should be replaced by a value which is derived from a radio group in the same data block.
    For Ex: ( )radio1 ( )radio2
    before i click on the push button, I'll select one of the radio button above,so my question is how to assign this radio group value to the bind variable in the sql statement in the LOV?
    Pl any hint is appreciated!
    Thanks
    Reddy

    The variable can be taken into account in the SELECT order contained in the Record Group used by the LOV.
    e.g. Select ... From ... Where column = :block.radio_group ...Francois

  • OBIEE direct DB request query sql statement cannot be edited after saved

    I have created direct DB request with long complex query, validated sql and Results appears ok. After I save this request and go back to edit the SQL statement, the original statement is only partially visible. Basically I can not do edit.
    Is there any Query related buffer or other configuration parms I have to set up?

    I'm not sure what the deal is between Flex/AIR and Visusal Studios, but i descided to publish my webservices and point the wsdl there instead of using the visual studio generated one.
    AND BEHOLD
    I't worked and worked much much faster than i was anticipating.
    So i'll just chalk it up to poor communication between FLEX and VS.  But if anybody knows a more complete answer I would still love to hear it.

  • Bind variables in DB Connect SQL Statement in Oracle

    We are looking for ways to improve performance of DB Connect extract from an Oracle database.
    An example command that is created by the Info-Package using a DB-Connect:
    Current
    SELECT "A", "B", "C", "D", "E", "F", "G", "H"
    FROM "GSF_BW"."V_BW_FORCAST_FACT"
    WHERE ("A" = '200904') AND ("B" BETWEEN '100801' AND '101412')
    The calculated cost (calculated by Oracle Optimizer) is 25.145
    Oracle recommends the usage of bind-variables.
    In that case the Statement would need to look like:
    SELECT "A", "B", "C", "D", "E", "F", "G", "H"
    FROM "GSF_BW"."V_BW_FORCAST_FACT"
    WHERE ("PG0R_SUBD" = :b1) AND ("ZCALMONTH" BETWEEN :b2 AND :b3)
    This would reduce the cost to 11.000 which is 40% of the statement before.
    My question now is: Can anything be done to influence the generation of the SQL statement to make it better performing?

    Hi,
    It is always better to test yourself. Using bind variable is always a good practice and optimizer avoids hard parsing (soft parsing will be done here) if bind variables are used.
    So yes, if this function is being executed several times frequently then second execution onwards it may run faster.
    If you want to see actually what is happening behind it, trace it (using tkprof) and see the result.
    See the below link to know more about SQL TRACE and tkprof.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e16638/sqltrace.htm#PFGRF01020
    Regards,
    Avinash
    Edited by: Avinash Tripathi on Nov 16, 2010 11:46 PM

  • Substitution variables by executing a SQL statement

    If there is a "&text" in a SQL Statement, then SQLDEV automatically interprets this as an "substitution variable" and pops-up a box for entering the values of the variable(s) or takes the value of the "define myvariable myvalue;" statement. How can I turn this feature off? Is there a preference or a SQL-Plus Statement, so that SQLDEV ignores the "&variables"?
    Cause: I have to run some (large) SQL-skripts, which contain some "&text", which should NOT be interpreted as substitution variables.

    SET DEFINE OFF
    SS

  • Use of Bind Variable in the Query of view object giving null pointer excep

    I am using this code in the backing bean of my page to set the value of the bind variable 'cmdID' in the view object.
    String AM = "model.UnixCommandsAppMod";
    String CF = "UnixCommandsAppModLocal";
    ApplicationModule am = Configuration.createRootApplicationModule(AM, CF);
    ViewObject vo = am.findViewObject("Command_options_view");
    vo.setNamedWhereClauseParam("cmdID", 1);
    vo.executeQuery();
    On the fifth line it is giving NullPointer exception.
    I am not being able to figure out the reason.

    User,
    a). Don't keep posting new questions in the same thread. It really does decrease the usability of the forum. Now, if someone searches for "INFO: ADF Faces is running with time-stamp checking enabled," they will find a post about null pointer exception in a bind variable and think, "oh, that doesn't apply to me." If your question is answered, mark the answer as correct. New questions go into a new thread. Kind of funny that the thread I pointed you to with the answer to your question also has this same admonishment.. ;)
    b). I'll relent and answer your new question. Ignore that INFO message. It is not an error. It will ALWAYS ALWAYS appear when you run your application in the embedded OC4J with JDeveloper. Had you searched the forum for "INFO: ADF Faces is running with time-stamp checking enabled" you would find that the first hit (among some others) has this same answer
    John

  • Create object name using a String variable

    Hi,
    I�m making a jsp page and I need to add several objects to a vector. The vector's name is arrayGrupo, and the object is Grupo. The problem is that when I create the instance of the object, I cant �give him different names, so the add in the Vector will always be of the same object instance. Is there anyway to create an object name using a variable?
    Something like this:
    <% if (request.getParameter("grupoNome") != null ) {
                                       nomeG=request.getParameter("grupoNome");
                                       descG=request.getParameter("grupoDesc");
                                       int nG=arrayGrupo.getTamanho(); //size of the array
                                       String xpto=String.valueOf(nG);
                                       Grupo "xpto"= new Grupo(); //here is the problem
                                       xpto.setNomeGrupo(nomeG);
                                       xpto.setDescricao(descG);
                                       xpto.setIdgrupo(arrayGrupo.getTamanho()+1);
                                       arrayGrupo.addGrupo(xpto);
    }%>
    Thanks
    Rui Gon�alves

    I want to show a list of objects that are stored in a vector. But I also want to add objects to that vector. If I just want to add one object, I can use this code:
    <% if (request.getParameter("grupoNome") != null ) {
                                       nomeG=request.getParameter("grupoNome");
                                       descG=request.getParameter("grupoDesc");
                                       Grupo newGrupo = new Grupo(nomeG,descG,arrayGrupo.getTamanho()+1);
                                       arrayGrupo.addGrupo(newGrupo);
    %>
    What should I do if I want to add more than one object to the vector?
    I don�t know if I made myself clear but is quite hard to explain my problem.
    Thanks

Maybe you are looking for

  • Attachments are not sent correctly?

    When I send an email with an attachment, the recipient does not receive the attachment; even though I use the "send windows friendly attachments". This happens very often, specially when the recipient is a PC and uses any of the following servers: ho

  • Connect a phone to another phone

    Hello, I try to connect a phone to another phone with the bluetooth api (jsr 82). I have a phone which searches all bluetooth devices around him. After the user select one device and send something to the device via a l2cap connection. But the connec

  • Dreamweaver Not Displaying Properly

    Hello, I'm not a Dreamweaver expert by any stretch of the imagination, so this might not make sense, but I've got to try anyway. Several of my webpages on my website are displaying properly online, but in dreamweaver I can only see the template in th

  • Inspection Lot for Process Order without Header Material

    Guys, We have an scenario that we create a Process Order without Header material using T code CORO. Is it possible to assign or create  a Inspection lot for Process order? Regards, Senthilraja

  • Is html a way out?

    I have been using iWeb to post my photo galleries online and want to change a couple of things. Currently there are several galleries that go to a page with thumbnails. When clicking on a thumbnail I get a postcard size photo, even in the slideshow.