Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion GroupsGeneralPHPASPPerlColdFusionFlashHTML, CSS, ScriptsBrowsers

Webmaster Forum / ColdFusion / General CF Topics / March 2008



Tip: Looking for answers? Try searching our database.

Dynamic SQL!

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
avt2k8 - 26 Mar 2008 17:59 GMT
Hello all!

I need to build sql dynamic in cold fusion that combine three sql queries in
order to display the data result as following:

1. first query

select name, age, class
from student_t

Name | Age | Class
A | 6 | 1
B | 12 | 2
C | 8 | 3

2. second query
--Get subject data
select subject, class_number
from record_t
where class_number = 'value of above class column'

This query return one record
Example results
subject | class_number
Math | 1

subject | class_number
Reading | 2

subject | class_number
Science| 3

3. third query

select address, zipcode
from subject_t
where subject = '90'

In above query, subject is dynamic. It can be replaced by math, science or
reading depending on the second query.
For example:

select address, zipcode
from math_t
where math = '90'

Finally, I need the table that display the data from 3 above queries as
following:

Name Age Subject Address Zipcode
A 6
B 12
C 8

I have no clue how to do dynamic sql in Cold Fusion. Please help me out with
your cold fusion expertise. Thanks in advance.
Ian Skinner - 26 Mar 2008 19:16 GMT
>  I have no clue how to do dynamic sql in Cold Fusion. Please help me out with
> your cold fusion expertise. Thanks in advance.

The trouble here is that you do not want to do dynamic SQL and your
question has little bearing on the use of ColdFusion.  You are asking
about basic relational database concepts and how to do a join query
(inner join to be precise) and would apply to any technology that
communicates to a database with SQL.

The standard reference for basic SQL questions such as this is Ben
Forta's "Teach Yourself SQL in 10 minutes".  It is a very good book that
covers the fundamentals of SQL syntax and logic.  Also there are more
web sites then you can shake a cat-5 cable at that will walk you through
building a basic table join.  Just type "SQL Inner Join" into your
favorite search engine.

The basic idea is this.

SELECT
  aField, bField, cField

FROM
  aTable
    INNER JOIN bTable ON aTable.aKey = bTable.aKey
    INNER JOIN cTable ON bTable.bKey = cTable.bKey
    INNER JOIN dTable ON aTable.cKey = dTable.cKey

Each table you add does increase the complexity considerable.  And if
you start mixing OUTER JOIN's into this be prepared to work very
methodically.

It is best to start with a single table, make sure you are getting the
correct data from that table.  Then add the next and confirm that you
are continuing to get the correct data before adding the next table.
Keep working table by table.

NOTE:  I did not discuss CFML anywhere in this post.  All this logic
would apply to SQL used in CFML, ASP, JSP, C++, Java, smalltalk,
anything that talks to a database.
avt2k8 - 26 Mar 2008 19:58 GMT
Hi,

Thanks for your reply. The reason why I could not use JOIN because all the
tables do not have the same column name. I got this assignment from other
persons.  I am newbie with Cold Fusion, they said needing to build the dynamic
SQL based on previous value results. I just submitted that questions and need
for helping at this forums. Any other suggestions how to solve this issue, I
appreciate it. Thanks for your time.
Ian Skinner - 26 Mar 2008 21:25 GMT
>  Thanks for your reply. The reason why I could not use JOIN because all the
> tables do not have the same column name.

The columns do not need the same name! They just need the same value
that means the same thing in the two related tables.  If you can build a
'dynamic' query as your mentor is suggesting, then 98.5% of the time you
can build a join query.  And this will almost always out preform a
'dynamic' solution that makes multiple requests to the database.

FROM aTable INNER JOIN bTable ON aTable.george = bTable.gracie

> I got this assignment from other
> persons.  I am newbie with Cold Fusion, they said needing to build the dynamic
> SQL based on previous value results.

Then you just reference the result variable from one query in the sql of
the following query.  If you need to know how to use variables in
ColdFusion then you probably should check out some of the introductory
documentation that is available with every installation of ColdFusion as
well as all over the internet.

<cfquery name="first" dsn="foobar">
SELECT aField
FROM aTable
</cfquery>

<cfdump var="#first#">

<cfoutput query="first">
  <cfquery name="second" dsn="foobar">
    SELECT bField
    FROM bTable
    WHERE bTable.gracie = <cfqueryParam value="#first.george#"
cfsqltype="cf_sql_integer">
  </cfquery>

  <cfdump var="#second#">
</cfoutput>

This is generally consider poor code taking many more lines and a lot of
bandwidth to accomplish the same thing that a simple join can do.
avt2k8 - 27 Mar 2008 02:43 GMT
Hi,

Thank for your advice about JOIN and dynamic SQL information. I am really
newbie with coldfusion, thus I am not sure how to apply to my real example that
I posted originally. If posible, please help me with above example code. Thanks
again.
-==cfSearching==- - 27 Mar 2008 03:26 GMT
> I am really newbie with coldfusion, thus I am not sure how to apply to my
real
> example that I posted originally. If posible, please help me with above
example code.

The previous two responses were _very_ detailed.  Read them over and then give
it a shot.  As mentioned, the JOIN's are pure SQL, not ColdFusion.  If you are
unfamiliar with basic database and sql concepts, I would suggest you start with
a tutorial like the one here
http://www.w3schools.com/sql/default.asp

BTW, is this a homework assignment?
Azadi - 27 Mar 2008 03:27 GMT
as Ian said before, this has NOTHING to do with CF. it is basic SQL.

as Ian also said before, you build a JOIN not on same name columns, but
on columns whose data is RELATED (that's why they are called
'relational' databases) - columns that have same DATA.

in your particular case a single JOIN query can easily replace your
first 2 queries, but with the third one it is questionable and depends
on your data base structure... but i doubt it can be JOINed in a query...

now, if your requirement is to have separate dynamic queries and have it
that way and no other way (i.e. you can't impress your supervisor with a
single JOIN query because he will not be impressed by it but instead
consider it a failed assignment bc you did not follow the requirements):

basic logic is:

- build your first query using <cfquery> tag
- <cfoutput query="firstqueryname"> - you do not need to output the
query data here yet, just the cfoutput tags so you can access the first
query's data...
- inside the cfoutput block build your second query, referencing the
dynamic variables in it using #firstqueryname.columnname# or
#firstqueryname['columnname']#
- <cfloop> through your second query's resultset (note: you are still
inside the <cfoutput> of the first query, so you can't use <cfoutput
query=secondqueryname"> here)
- inside the cfloop build your third query, referencing the dynamic part
in the same way as above
- out put required data
- close all open tags (</cfloop></cfloop></cfoutput>)

now try that and then come back if you have specific problems - do not
expect someone else to write the code for you.

Azadi Saryev
Sabai-dee.com
http://www.sabai-dee.com/
avt2k8 - 27 Mar 2008 04:45 GMT
Thank Azadi for showing me the way to do it! I got basic SQL JOIN knowledge and
just verified them in http://www.w3schools.com/sql/default.asp. For example:

SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

In this above query, having same fieldname: Employee_ID in two table Employees
and Orders in order to INNER JOIN.

In my post, my tables never had same fieldname. Ian said
FROM aTable INNER JOIN bTable ON aTable.george = bTable.gracie

I am not sure why he used george and gracie? are these the column name or
value???. Azadi was right that I need to build a JOIN on two different name
columns which have some same values. Anyway, ve learn and broaden my knowledge.
Tthank for all your help.  
 

Look in my post, any two different tables never have the same column
fieldname.

I never see an example that INNER JOIN on different column name that Ian said
in his post.
Azadi - 27 Mar 2008 04:56 GMT
once again, the TABLE/COLUMN NAMES do not matter at all. Ian used
'goerge' and 'gracie' column names as an example of the above.

the ONLY thing that matters is that the JOINed columns have SAME DATA.

for you example you should be joining the CLASS and CLASS_NUMBER columns
as they have same data.

Azadi Saryev
Sabai-dee.com
http://www.sabai-dee.com/
avt2k8 - 27 Mar 2008 14:33 GMT
Hello Azadi,

I have applied your instruction to build the code as following:
========================================================
<cfquery name="get_level_list" datasource="#primarydatasource#">
  select mail_split_code,sort_level, label_list
  from z_ct_sortation_t
  where mail_split_code in (select distinct mail_stream_split_ind
                           from uff_dtl_in_vw
                           where electronic_file_id = '#ElectronicFileID#')
                                        and label_list <> 'Mailpiece'
                                        order by sort_level
</cfquery>
             
<cfoutput query = "get_level_list">
     <cfloop>
      <cfquery name="get_labellist" datasource="#primarydatasource#">
        select label_list_name, zip_column_name from z_labellist_t
        where label_list_name = #get_level_list.label_list#
      </cfquery>
          <cfloop>
               <cfquery name="get_city_st" datasource="#primarydatasource#">
               select label_dest_zip_code,label_id,state_abbr
               from #get_labellist.label_list_name#_t
               where
                   <cfif #get_labellist.zip_column_name# eq
"three_dig_zip_code">
       three_dig_zip_code = #Mid(entry_zip_code,1,3)#
      <cfelse>                    
                   five_dig_zip_code = #entry_zip_code#
    </cfif>  
               </cfquery>
               <table>
    <tr>
                    <th>CITY</th>
                    <th>STATE</th>
                    <th>DEST ZIP</th>
    </tr>  
    <tr>
                    <td>#label_dest_zip_code#</td>
                    <td>#label_id#</td>
                    <td>#state_abbr#</td>
    </tr>
               </table>  
             </cfloop>
             </cfloop>
            </cfoutput>
=====================================================
I got the error at <cfloop> when I execute the code as belowed

Error Occurred While Processing Request  
Attribute validation error for tag CFLOOP.  
The tag has an invalid attribute combination: . Possible combinations are:
Required attributes: 'from,index,to'. Optional attributes: 'step'.
Required attributes: 'condition'. Optional attributes: None.
Required attributes: 'query'. Optional attributes: 'endrow,startrow'.
Required attributes: 'index,list'. Optional attributes: 'delimiters'.
Required attributes: 'collection,item'. Optional attributes: None.
 
 
The error occurred in report.cfm: line 378
 
376 :              
377 :              <cfoutput query = "get_level_list">
378 :              <cfloop>
379 :              <cfquery name="get_labellist"
datasource="#primarydatasource#">
380 :              select label_list_name, zip_column_name from z_labellist_t

Please take a look on my code and let me some more advices. Thanks
Ian Skinner - 27 Mar 2008 14:51 GMT
> Hello Azadi,
>
>  I have applied your instruction to build the code as following:
>  ========================================================
>  <cfoutput query = "get_level_list">
>       <cfloop>
...
>  Error Occurred While Processing Request  
>  Attribute validation error for tag CFLOOP.  
[quoted text clipped - 4 lines]
>  Required attributes: 'index,list'. Optional attributes: 'delimiters'.
>  Required attributes: 'collection,item'. Optional attributes: None.

If you compact your message to these key points does it not make sense
what the problem is?

If all else fails, this would be quickly resolved with a check of the
documentation on the relevant code.
avt2k8 - 28 Mar 2008 14:05 GMT
Finally, I solved all errors. Thanks for all your responses.
ncvoss@gmail.com - 27 Mar 2008 15:12 GMT
When you cfoutput over a query you don't need a loop underneath it.
cfoutput with a query acts as a loop.

Nick
-==cfSearching==- - 27 Mar 2008 05:02 GMT
> Azadi was right that I need to build a JOIN on two
> different name columns which have some same values.

Yes.  Ian said the same thing.

> I am not sure why he used george and gracie? are these
> the column name or value???.

They are column names.

> I never see an example that INNER JOIN on different
> column name

Probably because it would make the example harder for a beginner to
understand.  Also because well designed databases usually do use the same names
for related columns. For the same reason: it is easy to understand which
columns are related.  However, as Azadi and Ian said, it is not mandatory.  The
related column names [b]can[/b] be different.  

Take the join example from http://www.w3schools.com/sql/sql_join.asp

Say you renamed the Employee_ID column in the first table to
"Old_Employee_ID_Column"

Employees:
Old_Employee_ID_Column     Name
01     Hansen, Ola
02     Svendson, Tove
03     Svendson, Stephen
04     Pettersen, Kari

Orders:
Prod_ID      Product      Employee_ID
234     Printer     01
657     Table     03
865     Chair     03

Change the column name in the query and it will still work. Because what
matters is the values [i]inside[/i] the columns (ie 01, 02, 03), not the their
names.

SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.[b]Old_Employee_ID_Column[/b]=Orders.Employee_ID
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2010 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.