Ejecutar archivo .sql en  CFQUERY

Buenos dias no se si alguien sepa si se puede ejecurar el comado:
source archivo.sql dentro de un CFQuery y si alquien sabe que por favor me indique

<cffile action = "read" file = "c:\temp\archivo.sql"  variable = "sqlString">
<cfquery name = "result" dataSource = "myDSN">
    #sqlString#   
</cfquery>

Similar Messages

  • Agregar informacion a un archivo.sql

    Buenas noches estoy utilizando el CFFILE para modificar un archivo .sql que estoy creando al hacer una backup para no me agrega la infomacion que le estoy pasando la sentencia que estoy usando es la siguienteÑ
    <cffile action=append file="ruta" output ="Algo">

    Buen dia muchas gracias por la respuesta pero estoy en el parametro FILE le estoy pasando la ruta donde esta el archivo, solo que no se porq no me esta haciendo nada no le esta agregando lo que le estoy diciendo:
    <cffile action="append" file="C:\Copias\ejemplo.sql" output="Algo">
    pero no esta haciendo nada o si saben de otra forma por favor alguien que me ayude.

  • ¿como ejecutar archivos externos desde mi presentación con flash?

    Muy buenos días tengan todos los presentes, lo que pasa es que quiero hacer una presentación utilizando el adobe flash cs6 y en ella quiero al darle click a un botón cualquiera que me abra un documento en pdf guardado en una carpeta especifica, he investigado por muchos lugares pero no he podido dar con una solución, si alguien sabe como le agradecería de todo corazón el que me ayude con dicho pedido, que tengan un buen día

    Hola rAs:
    El MD5 NO es un programa, es un algoritmo de
    encriptación, es decir, una
    fórmula matemática que se aplica a cada uno de los
    caracteres para
    transformarlos en valores encriptados, por tanto, aunque lo
    diga el guru
    Chambers, no te sirve para proteger tus archivos swf.
    Existen no obstante utilidades que pueden ayudarte a
    protegerlos, pero lo
    cierto es que no tiene mucho sentido exponer algo en internet
    y luego
    protegerlo, de hecho cualquiera de ésas utilidades son
    vulnerables y ante un
    ataque de un buen cracker es casi imposible proteger tus
    archivos.
    Salu2
    `8¬}
    Juan Muro
    "rAs_" <[email protected]> escribió en
    el mensaje de noticias
    news:ft0nc7$og4$[email protected]..
    > Buenos d?as mi nombre es Denisse, es primera vez que
    posteo, no tengo
    > conocimiento avanzado del tema por ello quiero solicitar
    ayuda a ustedes.
    >
    > Hace un tiempo estoy buscando la forma de proteger mis
    archivos swf, de
    > alguna
    > forma gratuita si es posible, buscando encontr? este
    archivo pdf titulado
    >
    > ?La seguridad en Macromedia Flash MX
    > por Mike Chambers
    > Marzo del 2002?
    >
    > Como les dije no tengo mucho conocimiento as? que entre
    todo lo que pude
    > entender claramente, me pareci? importante lo que
    refer?a al programa MD5
    >
    > Lo baje desde el link, y subi sus archivos a la carpeta
    ra?z de mi hosting
    > justamente donde se encuentra el archivo swf que quiero
    proteger.
    >
    > Hasta ah? todo bien, pero que hago ahora?, busque un
    tutor?al pero estaba
    > en
    > ingles y he buscado pero no he encontrado nada mas en
    espa?ol, todo se
    > complica por que no se mucho de programaci?n .
    >
    > Mi preguntas son las siguientes, como hago para que se
    haga efectivo la
    > encriptaci?n y decodifique mi archivo swf? Que script
    debo poner y donde?
    > En
    > general no se que hacer estoy s?per perdida con este
    asunto, pero lo
    > necesito
    > enormemente.
    >
    > Si alguien puede ayudarme, estar? muy agradecida
    > Saludos Denisse.
    >
    >
    >
    >

  • Error al ejecutar SQL plus y error ORA-03114

    Instali Oracle 9i 9.2 cliente sobre windows 98 para conectarme a la base Oracle 7.3.4. La instalacisn fue exitosa y la configuracion del Net tambiin results exitosa, sin embargo, al ejecutar el sql plus me envma un error y hace referencia a product_user_profile, ademas, no puedo ejecutar mi aplicacisn en VB enviando el error ORA-03114: no conectado a ORACLE.
    ?Qui me falta por configurar?.
    Al instalar Oracle 8i no presenta ningun error, funcionando todo exitosamente.

    Babblefish believes that your question translates to English as:
    "I installed Oracle 9i 9,2 client on Windows 98 to connect me to the base Oracle 7.3.4. The installation was successful and the configuration of the Net also was successful, nevertheless, when executing the SQL extra sends an error to me and makes reference to product_user_profile, in addition, I cannot execute my application in VB sending the Ora-03114 error: not connected to ORACLE. What I need to form. When installing Oracle 8i does not present/display ningun successful error, working everything."
    Assuming that's a proper translation, there are a couple of points:
    - The 9.2 client ins't certified to connect to a 7.3.4 database. There may well be random issues with this configuration.
    - product_user_profile indicates to me that your DBA may have set something up that prevents certain users/machines/applications/etc. from logging into the database. I'd try speaking with your DBA to see whether this is the case, and what you need to do to have the system changed.
    Justin

  • I need help, CFquery and SQL NOT BETWEEN

    OK I am building a hotel booking system as a college project and I'm having trouble with finding rooms that are available. Now I have got this working, to an extent, So to give you the bigger picture al try and lay this out the best I can so you can understand.
    This is my database structure:
    Bookings Table
    Rooms Table
    Customers Table
    BookingID
    BookingDateIN
    BookingDateOUT
    RoomID
    CustomerID
    RoomID
    RoomType
    RoomNumber
    RoomPrice
    Room Description
    CustomerID
    FullName
    AddressLine1
    AddressLine2
    PostalCode
    CarReg
    OK, now you can see how this is going to work with the Bookings Tables RoomID and CustomerID matching the others to make a relationship, simple databasing.
    Now I have a page that lets you select a date and then select how many days the customer wants to stay for. So the selected date will be put towards the BookingDateIN field and the calculated date will be put towards the BookingDateOUT in a NOT BETWEEN SQL statement.
    I have got this to work with some test data, how ever when I select a date range that is below the 5th day in any month it shows the rooms are booked and not available even though the test data does not contain any days below the 5th.
    This is my test data in the Bookings Table:
    BookingID
    BookingDateIN
    BookingDateOUT
    CustomerID
    RoomID
    1
    20/05/2010
    23/05/2010
    2
    2
    2
    26/05/2010
    28/05/2010
    1
    5
    And here is my code for the bookings page:
    <cfset CurrentPage=GetFileFromPath(GetBaseTemplatePath())>
    <cfif isDefined("FORM.SearchRooms")>
    <!-- adds the number of days to the selected date -->
    <cfset #CalDate# = #DateFormat( DateAdd( 'd', #FORM.SelDays#, #FORM.SelDate# ), 'dd/mm/yyyy' )#>
    <!-- Queries the Bookings table with a crazy NOT BETWEEN SQL Statement -->
    <cfquery name="Check_Rooms_RS" datasource="HotelBookingSystem" username="HBSuser" password="HBSpass">
        SELECT *
        FROM Bookings
        WHERE BookingDateIN AND
        BookingDateOUT NOT BETWEEN
        <cfqueryparam value="#FORM.SelDate#" cfsqltype="cf_sql_timestamp">
        AND
        <cfqueryparam value="#CalDate#" cfsqltype="cf_sql_timestamp">
    </cfquery>
    <!-- Now this is my beginner CFQuery'n lol it queries the Rooms table with the values output from the bookings query and loops, then I put a 0 at the end to have the correct SQL statement lol I'm trying -->
    <cfquery name="Rooms_RS" datasource="HotelBookingSystem" username="HBSuser" password="HBSpass">
    SELECT *
    FROM Rooms
    WHERE RoomID = <cfloop query="Check_Rooms_RS">#RoomID# OR </cfloop>0
    </cfquery>
    </cfif>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Hotel Booking System - User Manager</title>
    <link rel="stylesheet" type="text/css" href="../style.css"/>
    </head>
    <body>
    <div class="container">
        <div class="booking_choose_date">
             <cfparam name="PreSelDate" default="#LSDateFormat(Now(), 'dd/mm/yyyy')#">
    <cfif isDefined("FORM.SearchRooms")>
        <cfset #PreSelDate# = #FORM.SelDate#>
    </cfif>
            <cfform name="form1" width="375" height="350" action="#currentpage#">
    <!-- Date Picker -->
               <cfinput type="DateField" name="SelDate" label="Block out starts" width="100" value="#PreSelDate#" mask="DD/MM/YYYY">
    <!-- Day Picker -->
    <cfselect size="1" name="SelDays" required="Yes" message="Select days staying">
          <option value="1" selected>1 Day</option>
          <option value="2">2 Days</option>
          <option value="3">3 Days</option>
          <option value="4">4 Days</option>
          <option value="5">5 Days</option>
          <option value="6">6 Days</option>
          <option value="7">7 Days</option>
    </cfselect>
               <cfinput type="Submit" name="SearchRooms" value="Check" width="100">
            </cfform>
        </div>
         <cfif isDefined("FORM.SearchRooms")>
            <div class="search_results">
              <!-- Outputs the Bookings table RoomID values -->
                <cfoutput query="Check_Rooms_RS">
                     #Check_Rooms_RS.RoomID#
                </cfoutput>
              <!-- Outputs the Rooms table RoomID values -->
                <cfoutput query="Rooms_RS">
                     #Rooms_RS.RoomType#
                </cfoutput>  
            </div>
        </cfif>
    </div>
    </body>
    </html>
    Little help with this would be amazing !!

    I only skimmed this thread. But even ignoring the myriad of date issues, the queries have a serious "logic" problem.  If you think about it, does searching for rooms that are not reserved in a table that only contains reserved rooms really make sense? Say you have twenty (20) rooms.  If only two (2) of them are reserved (ie in the Bookings table), how is that first query supposed to account for the other eighteen (18)?
    It would make more sense to search the Bookings table for rooms that are reserved.  Then query your Rooms table for rooms not in that list (ie available).  Granted that is not a very efficient method for a real application. But should work for your purposes.
    This is my test data in the Bookings Table:
    Are you storing the booking dates as strings?  Dates should be stored in a date/time column.  Storing them as strings creates all kinds of problems. Not to mention it makes it more difficult to use your database's date functions.

  • 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!

  • Recuperara aplicación desarrollada con PL/SQL con HTML .

    Saludos, tenemos una aplicación que en su momento fue un caso de exito, se desarrollo usando Oracle 8 y la aplicación se hizo usando la libreria HTP.P(' ') para poder ejecutar PL/SQL y HTML, actualmente contamos con la versión 11g release 2 (11.2.0.10) y  el modulo de Oracle Busines Intelligence 11g, la pregunta es, con estos elemetos actuales estamos en posibilidades de poder volver a levantar la aplicación en mención. ????  Envío ejemplo de código:

    Hi,
    SInce the PL/SQL block is keyed in dynamically, you probably want to use the anonymous PL/SQL syntax for invoking it:
    // begin ? := func (?, ?); end; -- a result is returned to a variable
    CallableStatement cstmt3 =
    conn.prepareCall(“begin ? := func3(?, ?); end;”);
    // begin proc(?, ?); end; -- Does not return a result
    CallableStatement cstmt4 =
    Conn.prepareCall(“begin proc4(?, ?); end;”);
    SQLJ covered in chapter 10, 11, and 12 of my book furnish a more versatile dynamic SQl or PL/SQL mechanisms.
    Kuassi
    - blog http://db360.blogspot.com/
    - book http://db360.blogspot.com/2006/08/oracle-database-programming-using-java_01.html

  • Wierd SQL happening

    I'm using the following SQL statement
    <cfquery name="rscustomer" datasource="rayannesql">
    SELECT firstname, lastname, address
    FROM dbo.customer
    WHERE lastname = '%#FORM.lastname#%'
    Order By firstname
    </cfquery>
    when I type in a last name value, I know exists in the
    database into a search box, I get a blank page back.
    I don't understand why. I tried removing the WHERE clause and
    get all results back from the database

    if you are going to do a wildcard search using the % symbol
    you will need to use the LIKE operator instead of the = operator.
    Your SQL statement should look like:
    SELECT firstname, lastname, address
    FROM dbo.customer
    WHERE lastname LIKE ('%#FORM.lastname#%')
    ORDER BY firstname

  • Cfstoredproc vs. Exec (SQL Server) or Call (MySQL)

    Just out of curiosity...
    Why go through the process of adding a cfstoredproc with associated cfprocparams and cfprocresults when I could simply use EXEC or CALL commands?
    SQL Server
    <cfquery>
         exec spMyStoredProc param1,param2
    </cfquery>
    MySQL
    <cfquery>
         call spMyStoredProc param1,param2
    </cfquery>
    It sure would seem to be a lot simpler doing it this way.
    Could it have something to do with type validation or database server permissions?

    As you say, not all DBs will allow query access (indeed: an awful lot of them won't).
    Also... try running a proc that returns multiple recordsets using <cfquery>
    Plus the JDBC driver handles proc calls one way, and dynamic SQL statements another way.
    Using <cfquery> to call a proc is like using a hammer to drive in screws.  It's possible, but you're not using the right tool for the job.
    Adam

  • How do I do a runtime debug of a Coldfusion component file?

    My application has a Coldfusion component(cfc), CFM file and a lot of Flex source files.
    I tried using  <cftry>,  <cfcatch>, <cfdump> to find the errors in the cfc, but still cannot trace the issue.
    The code in CFC file is somewhat like
    <cfcomponent>
        <cffunction name="edit" access="remote" returntype="any">
            <cfargument name="form_data" type="struct">
            <cftry>
                <cftransaction>
                    <!--- Update Record --->
                    <cfquery datasource="#Application.ds#">
                        some SQL here
                    </cfquery>
                     <!--- Remove all previous outcomes --->
                    <cfquery datasource="#Application.ds#">
                        some SQL here
                    </cfquery>
                    <!--- Log Update --->
                    <cfquery datasource="#Application.ds#">
                        some SQL here
                    </cfquery>
                    <!--- Get Last Logged Record --->
                    <cfquery datasource="#Application.ds#" name="getLogLastRecord">
                        some SQL here
                    </cfquery>
                    <cfloop index="arr_index" from="1" to="#ArrayLen(form_data.num)#">
                        <!--- Update Record --->
                        <cfquery datasource="#Application.ds#" >
                            some SQL here
                        </cfquery>
                        <!--- Log Update --->
                        <cfquery datasource="#Application.ds#" >
                            some SQL here
                        </cfquery>
                    </cfloop>
        </cftransaction>
                <cfset result['statMsg']= "The record was saved successfully!">
                <cfset result['status']= true>
                <cfcatch><!--- Catch error --->
                    <cfsavecontent variable="contentSaver">
                         <cfdump var="#form_data#">
                         <cfdump var="#cfcatch#">
                    </cfsavecontent>
                    <cffile action="write" file="#ExpandPath('.')#\debug.html" output="#contentSaver#">
                    <cfset result['statMsg'] = cfcatch.Message>
                    <cfset result['status']= false>
                </cfcatch>
            </cftry>
            <cfreturn result>
        </cffunction>
    </cfcomponent>
    Issue: 1 My understanding is if the transaction is successful I should get the message "The record was saved successfully!" which I don't get, though the transaction is successful as the data is saved in the MySQL backend.
    Even if the transaction failed, I should get a message due to the catch block.
    What could be the reason I am not getting the message? The users of the application need to get this so that they know that the changes they did are saved.
    Issue 2: For another transaction, I get the below message at run time.
    "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@domain.com' at line 3"
    The transaction goes through fine and changes are saved to the back end database which means nothing is wrong in my SQL syntax.
    I don't see anything wrong on line 3 of the cfc file, nor the third line of the SQL statement has anything missing. Why am I getting that message?
    Why am I not getting a message when I should for Issue 1 when the transaction is successful and why am I getting a strange error message for Issue 2 though the transaction is successful?
    Can I do a run time debugging of the CFC using Coldfusion Builder as I can for Flex source files using Flexbuilder?
    Any advice would be welcome.

    hemant_k wrote:
    Yes, you can use debugger in ColdFusion Builder. Check http://help.adobe.com/en_US/ColdFusionBuilder/Using/WS0ef8c004658c1089 -31c11ef1121cdfd6aa0-7fff.html for some details.
    There are some interesting link around builder available on CF builder team blog - blogs.adobe.com/cfbuilder. [image links are not working becuase of admin issues]
    Thanks, that link is helpful.

  • Selecting Randoms from Query of Queries

    I can create a query that selects random records
    <cfquery....>
    select top 10 * from table order by newid() <!--- SQL
    Server --->
    </cfquery>
    or
    <cfquery....>
    select top 10 * from table order by rand() limit 10 <!---
    MySQL--->
    </cfquery>
    However, is there a way to cache a query then select random
    records from it?
    I want to cache the overall query that retrieves all the
    records, then
    randomly pull
    from that cached query.
    If I use newid() or rand(), the query bombs on the
    parentheses.
    Any suggestions?
    Tami

    well, it's not really a query of queries... more like a query
    of a cached
    query :)
    "DixieGal" <[email protected]> wrote
    in message
    news:ffsn1b$***$[email protected]..
    |I can create a query that selects random records
    | <cfquery....>
    | select top 10 * from table order by newid() <!--- SQL
    Server --->
    | </cfquery>
    |
    | or
    | <cfquery....>
    | select top 10 * from table order by rand() limit 10
    <!--- MySQL--->
    | </cfquery>
    |
    | However, is there a way to cache a query then select random
    records from
    it?
    | I want to cache the overall query that retrieves all the
    records, then
    | randomly pull
    | from that cached query.
    |
    | If I use newid() or rand(), the query bombs on the
    parentheses.
    |
    | Any suggestions?
    |
    | --
    |
    | Tami
    |
    |

  • Ajax checing for duplicte records

    i am trying to have a form in ajx that will also insert a new
    contact... i havit working with the insert part but i want to have
    it check for duplicate records before inserting the contact... here
    is the form ... and i also have a cfc for the functions
    <cfcomponent output="false">
    <cfset this.dsn="myserver">
    <!--- Populates the grower list Select --->
    <cffunction name="getCompany" access="remote"
    returntype="array">
    <cfset var rsData="">
    <cfset var myReturn=ArrayNew(2)>
    <cfset var i=0>
    <cfquery name="rsData" datasource="myserver">
    SELECT cid ,Company
    FROM Contacts
    order by Company asc
    </cfquery>
    <cfloop query="rsData">
    <cfset myReturn[rsData.currentrow] [1]=rsdata.cid>
    <cfset myReturn[rsData.currentrow] [2]=rsdata.Company>
    </cfloop>
    <cfreturn myReturn>
    </cffunction>
    <!--- Populates list related to grower --->
    <cffunction name="getcontacts" access="remote"
    returntype="array">
    <cfargument name="cid" type="string" required="no">
    <cfset var rsData="">
    <cfset var myReturn=Arraynew(2)>
    <cfset var i=0>
    <cftry>
    <cfquery name="rsdata" datasource="myserver">
    SELECT cid, Company, FullName, Lname, Fname, Address1,
    Address2, City, State, zip, country, Phone, ext, cell, Fax,
    tollfree, Web, Email, Title, ExecutiveTitle
    FROM Contacts
    WHERE Contacts.Company = '#arguments.cid#'
    </cfquery>
    <cfcatch type="any">
    <cfset returnStruct.success = false />
    <cfset returnStruct.message = cfcatch.message />
    </cfcatch>
    </cftry>
    <cfloop query="rsdata">
    <cfif rsdata.recordcount gt 0>
    <cfset myReturn[rsData.currentrow] [1]=rsdata.cid>
    <cfset myReturn[rsData.currentrow] [2]=rsdata.FullName>
    <!--- <cfelse>
    <cfset rsdata.cid = 999999>
    <cfset rsdata.FullName = 'none'>
    <cfset myReturn[rsData.currentrow] [1]=rsdata.cid>
    <cfset myReturn[rsData.currentrow] [2]=rsdata.FullName>
    --->
    </cfif>
    </cfloop>
    <cfreturn myReturn>
    </cffunction>
    <!--- Gets contact info for 2page
    contacts!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    --->
    <cffunction name="getcontactsinfo2" access="remote"
    returnType="struct">
    <cfargument name="growerName" type="string"
    required="no">
    <cfset var data="">
    <cfset var c = "">
    <cfset var s = structNew()>
    <cftry>
    <cfquery name="data" datasource="myserver">
    SELECT cid, Company, FullName, Lname, Fname, Address1,
    Address2, City, State, zip, country, Phone, ext, cell, Fax,
    tollfree, Web, Email, Title, ExecutiveTitle
    FROM Contacts
    WHERE Company= <cfqueryparam cfsqltype="cf_sql_varcar"
    value="#arguments.growerName#">
    </cfquery>
    <cfloop list="#data.columnlist#" index="c">
    <cfset s[c] = data[c][1]>
    </cfloop>
    <cfcatch type="any">
    <cfset returnStruct.success = false />
    <cfset returnStruct.message = cfcatch.message />
    </cfcatch>
    </cftry>
    <cfreturn s>
    </cffunction>
    <cffunction name="getcontactsinfo" access="remote"
    returnType="struct">
    <cfargument name="cid" type="numeric" required="true">
    <cfset var data="">
    <cfset var c = "">
    <cfset var s = structNew()>
    <cftry>
    <cfquery name="data" datasource="myserver">
    SELECT cid, Company, FullName, Lname, Fname, Address1,
    Address2, City, State, zip, country, Phone, ext, cell, Fax,
    tollfree, Web, Email, Title, ExecutiveTitle
    FROM Contacts
    WHERE contacts.cid= <cfqueryparam
    cfsqltype="cf_sql_integer" value="#arguments.cid#">
    </cfquery>
    <!--- --->
    <cfloop list="#data.columnlist#" index="c">
    <cfset s[c] = data[c][1]>
    </cfloop>
    <cfcatch type="any">
    <cfset returnStruct.success = false />
    <cfset returnStruct.message = cfcatch.message />
    </cfcatch>
    </cftry>
    <cfreturn s>
    </cffunction>
    <!--- Updates the database of grower contacts --->
    <cffunction name="markTaskComplete" output="false"
    returntype="struct" access="remote" hint="i mark a task
    complete">
    <cfargument name="cid2" type="numeric" required="true"
    />
    <cfargument name="company2" type="string" required="true"
    />
    <cfargument name="address2" type="string" required="true"
    />
    <cfargument name="city2" type="string" required="true"
    />
    <cfargument name="state2" type="string" required="true"
    />
    <cfargument name="zip2" type="string" required="true"
    />
    <cfset var qMarkTaskComplete = "" />
    <cfset var returnStruct = structNew() />
    <cfset returnStruct.success = true />
    <cfset returnStruct.taskID = arguments.cid2 />
    <cftry>
    <cfquery name="qMarkTaskComplete"
    datasource="myserver">
    UPDATE
    Contacts
    SET
    Company = <cfqueryparam value="#arguments.company2#"
    cfsqltype="cf_sq_varcar" /> ,
    Address1 = <cfqueryparam value="#arguments.address2#"
    cfsqltype="cf_sq_varcar" /> ,
    City = <cfqueryparam value="#arguments.city2#"
    cfsqltype="cf_sq_varcar" />,
    State = <cfqueryparam value="#arguments.state2#"
    cfsqltype="cf_sq_varcar" />,
    zip = <cfqueryparam value="#arguments.zip2#"
    cfsqltype="cf_sq_varcar" />
    WHERE
    cid = <cfqueryparam value="#arguments.cid2#"
    cfsqltype="cf_sq_int" />
    </cfquery>
    <cfcatch type="Database">
    <cfset returnStruct.success = false />
    <cfset returnStruct.message = cfcatch.message />
    </cfcatch>
    </cftry>
    <cfdump var="#returnStruct#"/>
    <cfreturn returnStruct />
    </cffunction>
    <cffunction name="lookupGrower" access="remote"
    returntype="array">
    <cfargument name="search" type="any" required="false"
    default="">
    <!--- Define variables --->
    <cfset var data="">
    <cfset var result=ArrayNew(1)>
    <!--- Do search --->
    <cfquery name="data" datasource="myserver">
    SELECT cid, Company, FullName, Lname, Fname, Address1,
    Address2, City, State, zip, country, Phone, ext, cell, Fax,
    tollfree, Web, Email, Title, ExecutiveTitle
    FROM Contacts
    WHERE (Company LIKE '#ARGUMENTS.search#%')
    </cfquery>
    <!--- Build result array --->
    <cfloop query="data">
    <cfset ArrayAppend(result, Company)>
    </cfloop>
    <!--- And return it --->
    <cfreturn result>
    </cffunction>
    <cffunction name="markTaskComplete2" output="false"
    returntype="struct" access="remote" hint="i mark a task
    complete">
    <cfargument name="company3" type="string" required="true"
    />
    <cfargument name="address3" type="string" required="true"
    />
    <cfargument name="city3" type="string" required="true"
    />
    <cfargument name="state3" type="string" required="true"
    />
    <cfargument name="zip3" type="string" required="true"
    />
    <cfset var qMarkTaskComplete = "" />
    <cfset var returnStruct = structNew() />
    <cfset returnStruct.success = true />
    <cfset returnStruct.taskID = arguments.cid />
    <cftry>
    <cfquery name="qMarkTaskComplete"
    datasource="myserver">
    INSERT INTO KYIntranet.dbo.Contacts
    (Company
    ,Address1
    ,City
    ,State
    ,zip)
    VALUES
    (<cfqueryparam value="#arguments.company3#"
    cfsqltype="cf_sq_varcar" /> , <cfqueryparam
    value="#arguments.address3#" cfsqltype="cf_sq_varcar" />
    ,<cfqueryparam value="#arguments.city3#"
    cfsqltype="cf_sq_varcar" />,<cfqueryparam
    value="#arguments.state3#" cfsqltype="cf_sq_varcar"
    />,<cfqueryparam value="#arguments.zip3#"
    cfsqltype="cf_sq_varcar" />)
    </cfquery>
    <cfcatch type="any">
    <cfset returnStruct.success = false />
    <cfset returnStruct.message = cfcatch.message />
    </cfcatch>
    </cftry>
    <cfreturn returnStruct />
    </cffunction>
    </cfcomponent>

    From my understanding your table that gets inserted is
    KYIntranet.dbo.Contacts . And i guess company field in that table
    needs to be checked for duplicates. So you can put the company
    field as primary key for that table. Inserting the same company
    name can result in a Primary key exception meaning that a duplicate
    has been entered. By this way you can check for duplicates.
    <cftry>
    <cfquery>Insert SQL code</cfquery>
    <cfcatch>
    <--Code to handle primary key exception-->
    </cfcatch>
    <cftry>

  • Problem while doing insert

    Hello.
    I'm trying to write the following String containing an XML document, in a MySql database:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ReporteHoras SYSTEM "ReporteHoras.dtd">
    <ReporteHoras>
    <Persona nombre="Daniel">
    <Fecha dia="1/11/2004" horas_teoricas="8">
    <Proyecto cod="001">
    <Tarea nombre="x">
    <Horas>8</Horas>
    </Tarea>
    <Tarea nombre="y">
    <Horas>5</Horas>
    </Tarea>
    </Proyecto>
    </Fecha>
    <Fecha dia="2/11/2004" horas_teoricas="7">
    <Proyecto cod="010">
    <Tarea nombre="z">
    <Horas>8</Horas>
    </Tarea>
    </Proyecto>
    </Fecha>
    </Persona>
    </ReporteHoras>
    And I get the following exception:
    (ReportesReceiver.HorasGMSReceiver 219 ) error al ejecutar tareas SQL: java.sql.SQLException: Syntax error or access violation, message from server: "You have an error in your SQL syntax near 'VALUES ('91750418', 'horasgms', '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!D' at line 1"
    4729468 [imqConsumerReader-0-8919380558701437696-0] ERROR starting.src.java.ReportesReceiver.HorasGMSReceiver - error al ejecutar tareas SQL: java.sql.SQLException: Syntax error or access violation, message from server: "You have an error in your SQL syntax near 'VALUES ('91750418', 'horasgms', '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!D' at line 1"
    java.sql.SQLException: Syntax error or access violation, message from server: "You have an error in your SQL syntax near 'VALUES ('91750418', 'horasgms', '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!D' at line 1"
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1697)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1083)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1142)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:1876)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1590)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1653)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1492)
    at starting.src.java.ReportesReceiver.HorasGMSReceiver$GMSListener.onMessage(HorasGMSReceiver.java:210)
    at com.sun.messaging.jmq.jmsclient.MessageConsumerImpl.deliverAndAcknowledge(MessageConsumerImpl.java:247)
    at com.sun.messaging.jmq.jmsclient.MessageConsumerImpl.onMessage(MessageConsumerImpl.java:210)
    at com.sun.messaging.jmq.jmsclient.SessionReader.deliver(SessionReader.java:76)
    at com.sun.messaging.jmq.jmsclient.ConsumerReader.run(ConsumerReader.java:153)
    at java.lang.Thread.run(Thread.java:534)
    It seems that the string contains some illegal characters, but I don't know where they are.
    I do the following to insert the data:
    java.sql.Connection conn = conexion.getDbConn();
    PreparedStatement pstmt = conn.prepareStatement(insertSQLString);
    pstmt.setString(1, processId.toString());
    pstmt.setString(2, "horasgms");
    pstmt.setString(3, contenido);
    pstmt.executeUpdate();
    Can anyone tell me what am I doing wrong?
    Thank you in advance.
    Regards.
    Dani.

    > > <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ReporteHoras SYSTEM
    "ReporteHoras.dtd">This is where the illegal character comes ... I think
    it has a problem with "!"
    ***Annie***Caller = aashu Site = unknown Caller Info. = singh Kind = level1 state = OPEN Errorjava.sql.SQLException: Syntax error or access violation, message from server: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' Project_Name, Client_Location, Client_Country, Client_Contract_HW INTO client_i' at line 1"
    codes as following:-
    <%@ page import="java.util.*,java.text.DateFormat, java.io.*,java.net.*,java.sql.*,java.sql.Connection,java.sql.DriverManager,java.sql.Statement"%>
    Caller = <%=request.getParameter("caller")%>
         <% String s = request.getParameter("caller");%>
         Site = <%=request.getParameter("site")%>
         <% String s2 = request.getParameter("site");%>
    Caller Info. = <%=request.getParameter("callerinfo")%>
         <% String s3 = request.getParameter("callerinfo");%>
         Kind = <%=request.getParameter("kind")%>
         <% String s4 = request.getParameter("kind");%>
    state     = <%=request.getParameter("state")%>
         <% String s5 = request.getParameter("state");%>
    <%
    try     
    { Class.forName("com.mysql.jdbc.Driver").newInstance();
                        // String connectionURL ="jdbc:mysql://localhost:3306/client_db1?user=;password=";
                   //Connection con = DriverManager.getConnection(connectionURL,"","");
         Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/client_db1?user=;password=","","");
         Statement st = con.createStatement();
    st.executeUpdate("INSERT Client_Name, Project_Name, Client_Location, Client_Country, Client_Contract_HW INTO client_info values('"+s+"', '"+s2+"', '"+s3+"', '"+s4+"', '"+s5+"')"); %>
    <%}
    catch(Exception e)
    { out.println("Error"+e);
    %>[b]

  • Capturing cfml execution time

    Hi, good day to all! Is there any way on how to capture an
    execution time of a cfm instruction? I have two situations, but I
    think they're similar as shown below:
    1st situation:
    <!--- start query --->
    <cfquery name = "q1" datasource="#db#">
    SQL statement
    </cfquery>
    <cfquery name = "q2" datasource="#db#">
    SQL statement
    </cfquery>
    <cfquery name = "q3" datasource="#db#">
    SQL statement
    </cfquery>
    <cfquery name = "q4" datasource="#db#">
    SQL statement
    </cfquery>
    <!--- end query --->
    For the 1st situation above, I want to capture the total
    execution time from q1 to q3 only. Also, I want to get the time
    each query is executed. Is there any way how?
    2nd situation (could be any cfml instructions):
    <!--- start cfml --->
    instruction 1............................
    instruction 2............................
    instruction 3............................
    instruction 4............................
    <!--- end cfml --->
    In the 2nd situation, I want to get the total execution time
    from instruction 1 to instruction 3 only.
    Any help is really appreciated. Thanks.
    Update ----------------------------------------
    By the way, I am using cf 6.1. It seems the gettickcount
    technique isn't returning the exact execution time. actually, i
    have a code in cf that contains a vbscript. that writes to an excel
    file. This is what i did:
    start:
    ..... cf tags here ...
    <cfset startTimer = GetTickCount()>
    <script language="vbscript">
    --- some vbscript and cf statements .........
    <cfoutput query = "some_query">
    objXL.ActiveSheet.Cells(X_Pos,1).Value = "#some_cf_value#"
    objXL.ActiveSheet.Cells(X_Pos,1).Font.size = "#FSize#"
    --- some vbscript and cf statements .........
    </cfoutput>
    --- some vbscript and cf statements .........
    </script>
    <cfset endTimer = GetTickCount()>
    <cfset totalTime_ms = endTimer - startTimer >
    end:
    totalTime_ms doesn't seem to return the exact length of time
    of the process. I mean, From one test, I tried to use a stopwatch
    and found out it took about 30 seconds to complete filling the
    excel file. But totalTime_ms returns only about 1500 ms, which is
    only about 1.5 seconds. The result is far from reality. Why? Is
    there any other way? Thanks.

    if you wanna know the execution time of the whole page, here
    is coding..
    put this
    <cfset tickBegin = GetTickCount()> on the top row of ur
    page.
    put this
    <cfset tickEnd = GetTickCount()>
    <cfset loopTime = tickEnd - tickBegin>
    <cfset loopTime = loopTime / 1000>
    <cfoutput>Messages Results #count_first# - #count_end#
    of about #ListLen(session.topic_replies_list)# for seconds
    milliseconds. (#loopTime# seconds)</cfoutput>
    at the bottom row of ur page.

  • Message Profanity Sniffer

    I've got an internal bulletin board and a guestbok for my CF site.  I established a table in my Access database called smut, which also contains other choice words.  The list is growing, however, I wish to filter out messages containing anything in the database smut table.  I also wish to create another listing (template) displaying the messages with the unwanted terms.  Though, this is more an SQL thing, what can CF do?
    Now, using the CFIF, it would be quite laborious to have a CFIF instance for each unwanted term.  CFLOOP would require the listing be delimited in the LIST attribute for CFLOOP, which negates the use of the database smut table, right.  How would you suggest referencing the smut table to use for filtering in CF?
    Doug

    Close, but I can spot a couple things wrong with the logic there right off the bat:
    1) Your code is missing the INSERT statement in order to add the data to your database (on success) - without it your user's post will never make it into your system
    2) You need to make the message that appears after the validation runs conditional on the results of the validation.  As you've coded it now, your "success" message is hard coded so that it appears regardless of whether the validation has passed or not.
    Try the following blueprint:
    <!--- Set Default Values --->
    <cfset bValidationPassed = true>
    <cfset sMessage= "">
    <!--- Retrieve Words --->
    <CFQUERY NAME="q_profanity" DATASOURCE="9130.ww">
    SELECT term
    FROM profanity;
    </CFQUERY>
    <!--- Detect the use of stored words --->
    <cfloop query="q_profanity">
         <cfif FindNoCase(term, form.gb_entry_m)>
               <cfset bValidationPassed  = false>
              <cfbreak>
         </cfif>
    </cfloop>
    <!--- Conditional logic depending on whether profanity term was detected --->
    <cfif bValidationPassed eq true>
         <!--- No profanity: add post --->
         <CFQUERY NAME="q_AddRecord" DATASOURCE="9130.ww">
           [INSERT SQL HERE]
         </CFQUERY>
         <!--- Set message  text --->
         <cfsavecontent variable="sMessage ">
         <p>Your guestbook message has been saved.</p>
         <!--- you will need to determine the new entry ID in the Add Record SQL above --->
         <p><A HREF="gb_entry_rvw.cfm?call_number=#gb_entryID#">Review Your Entry Now!</A></p>
         </cfsavecontent>
    <cfelse>
         <!--- If profanity detected, show error text --->
         <cfset sMessage = "You have included a term or phrase which is unacceptable to our records in your guestbook message. ">
    </cfif>
    <!--- Generate output HTML --->
    <HTML>
    <HEAD>
    <TITLE>New Guestbook Entry</TITLE>
    </HEAD>
    <BODY>
    <!--- display message --->
    <cfoutput>#sMessage#</cfoutput>
    </BODY>
    </HTML>

Maybe you are looking for