ColdFusion: How to insert a list with a static foreign key in one insert?

前端 未结 4 1415
北海茫月
北海茫月 2021-01-21 10:45

I have a list like this thing1,thing2,thing3. And I want to insert them into a look-up table with the same foreign key. So ideally it would look like this:



        
4条回答
  •  北海茫月
    2021-01-21 10:47

    Update:

    Ultimately the real problem here was that the feature of inserting multiple sets of values with a single VALUES clause is only supported in SQL Server 2008+ and the OP is using 2000. So they went with the select / union all approach instead.


    (Expanded from the comments)

    Sure you can loop inside a cfquery. All cfml code is processed on the CF server first. Then the resulting SQL string is sent to the database for execution. As long as your CF code results in a valid SQL statement, you can do just about anything you want :) Whether you should is a different question, but this kind of looping is perfectly fine.

    Getting back to your question, just switch to a from/to loop instead and use list functions like getToken(list, index) to get the individual elements (see Matt's example) or use an array instead. Obviously you should also validate the list is not empty first. My personal preference is arrays. Not tested, but something like this:

        
    
        
           INSERT INTO lkp_things (foreign_key, thing) VALUES
           
               ,
               ( 
                  
                    
                 ,  
               )
           
        
    

    Having said that, what is the source of your #thing# list? If those values exist in a database table, you could insert them directly with a SELECT statement, instead of a loop:

           INSERT INTO lkp_things (foreign_key, thing) 
           SELECT , thing
           FROM   ThingTable
           WHERE  thing IN 
                  (
                     
                  )
    

提交回复
热议问题