Skip to main content
Known Participant
January 21, 2010
Question

Inserting structure to table

  • January 21, 2010
  • 2 replies
  • 1162 views

I'm getting this value through a loop of a structure:

<cfloop collection="#st_datachanged#" item="key">

  <cfoutput>

  #key# - #st_datachanged[key]#<br>

  </cfoutput>

</cfloop>

Gender - F
LastName - Smith
FirstName - Adrienne
Addr1 - 9721 Willow Lane
City - Potomac
Zip - 20854-2053
State - MD

How can I insert this value into a row in my table?

My table row has these columns: FirstName,LastName,Gender,Addr1,City,State,Zip,Gender

I'm using CF8 and Sybase

This topic has been closed for replies.

2 replies

BKBK
Community Expert
Community Expert
January 22, 2010

I have kept it generic. It will work generally for any struct, as the keys don't have to be spelled out.

I have assumed all the data is of string type. You may want to take the challenge to make the code more efficient.

<!--- comma-delimited list of keys --->
<cfset keyList = structKeyList(st_datachanged)>

<cfset keyValueList = "">
<cfset counter = 1>

<!--- create comma-delimited, single-quoted values of respective keys --->
<cfloop List="#keyList#" index="listItem">
    <cfset keyValueList = keyValueList & "'#st_datachanged[listItem]#'">
    <cfif counter LT listLen(keyList)>
        <cfset keyValueList = keyValueList & ",">
        <cfset counter = counter + 1>
    </cfif>
</cfloop>

<!--- insert row to table --->
<cfquery name="yourQueryName" datasource="yourDSN">
insert into yourTable(#keyList#)
values (#preserveSingleQuotes(keyValueList)#)
</cfquery>

Inspiring
January 22, 2010

Regarding:

It will work generally for any struct, as the keys don't have to be spelled out.

I have assumed all the data is of string type.

Did you also assume that none of the values contain apostrophes?

BKBK
Community Expert
Community Expert
January 22, 2010

@Dan Bracuk

Did you also assume that none of the values contain apostrophes?

You got me there, Dan. Yes, I did also assume none of the values contain apostrophes.

Inspiring
January 22, 2010

insert into yourtable

(firstname

, lastname

etc)

select distinct #firstname#

, #lastname#

etc

from somesmalltable

where not exists

(subquery to prevent duplicates)

but with cfqueryparam, checking for nulls, etc.