Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

How to delete multiple rows at once

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    How to delete multiple rows at once

    I could use some advice on best practice of deleting multiple rows from multiple tables at once from a delete button on a grid.

    My scenario is a contact table with id# and name that is related to several subtables containing additional info such as telephone #, address, etc.

    Therefore, a common scenario would be attempting to delete all of the following at once based on primary key id# of 1776:

    Contacts Table:
    (one row)
    1776 - George Washington

    Address SubTable:
    (2 rows)
    1776 - 1300 Pennsylvania Ave, Washington, D.C. 01010
    1776 - 2000 Cherry Tree Drive, Valley Forge, PA 23141

    Telephone SubTable:
    1776 - 800-123-1234
    1776 - 800-321-4321

    What I have tried is views - do not work with my backend of Postgres because they are read only.

    When the delete Javascript button is placed on the grid for the Contacts toplevel of 1776 - George Washington, an obvious database error of not allowing delete because of related rows in the other tables.

    Thanks for the help.

    #2
    Re: How to delete multiple rows at once

    Couldn't you setup your database to delete the child records for you when the primary record is removed using foreign keys? Does PostgreSQL have Foreign Key constraints?
    Last edited by TheSmitchell; 07-28-2013, 05:06 PM.
    Alpha Anywhere latest pre-release

    Comment


      #3
      Re: How to delete multiple rows at once

      Hi Sarah,

      Have you set up relationships and set the options to cascade the delete? I am not familiar with PostGreSQL, but that is what I would do in MSSQL.

      Hopefully that will point you in the right direction at least.

      Regards,

      Phil

      Cascade.jpg

      Comment


        #4
        Re: How to delete multiple rows at once

        Of course that supposes you wish to delete the primary record too.

        If not, then perhaps an AJAX call back with

        DELETE FROM PHONES WHERE FKID = MTPK
        DELETE FROM ADDRESS WHERE FKID = MTPK

        FKID = Foreign key ID and MTPK = Master Table Primary Key

        Just some thoughts

        Phil

        Comment


          #5
          Re: How to delete multiple rows at once

          hello andrew
          i use mysql, so no expert on postgresql.
          but the documentation says
          you could have two types of foreign key constraints:
          1> REFERENCES ... ON DELETE RESTRICT
          2> REFERENCES ... ON DELETE CASCADE

          so you should be able to delete on deletion of the primary table the foreign key will do what you want to do.

          however you could also leave the default and trap when the user wants to delete a primary record that has child record, you could prompt a warning and if they insist then you can delete the primary record and the child records using xbasic. better yet add a field and record that field and keep the records out of view but not deleting them as a safety measure.

          the primary key can be obtained from the e. object
          the sql delete statement can be constructed using that primary key.
          thanks for reading

          gandhi

          version 11 3381 - 4096
          mysql backend
          http://www.alphawebprogramming.blogspot.com
          [email protected]
          Skype:[email protected]
          1 914 924 5171

          Comment


            #6
            Re: How to delete multiple rows at once

            Second thought is to write your own set of DELETE and execute it in the afterDeleteRecord event. e.dataSubmitted and e.oldDataSubmitted are both available there. Though, personally, I think using foreign key constraints are a better solution.
            Alpha Anywhere latest pre-release

            Comment


              #7
              Re: How to delete multiple rows at once

              Thank you for all of the well thought out answers. I consistently fall in the rut of trying to do everything in Alpha rather than off loading some of the work to the Postgres backend.

              I think I am leaning towards Phil's suggestion as I simplified the question more than reality. Although never having programmed an ajax callback, I think this may work better because:

              The Contact ID# is potentially contained in many other tables such as Timesheets, TakeOff, WorkOrders, Maintenance, etc.
              The contact may also just simply show up in the Contact table if it is just a person we need to track phone, address, etc.
              But also, the contact may show up in all of the other tables if it ended up being a customer/job/project.

              Therefore, I think I can conjure some better logic by checking to see if the Contact ID# shows up in those other tables, and if not, going ahead and deleting the Contact in the contact tables as well as the closely related address, phone tables.
              Otherwise, if the Contact# does exist in the Timesheets, TakeOffs, etc, not allow the contact to be deleted in any table.

              I see it working in my head, now if I can muster the neurological power to make it work. Cascading deletes give me the major willies though too. Seems like an easy way to miss some logic and wipe out a lot of data if I don't get things designed correctly.

              Many thanks for the help....now on to my first Ajax callback

              Andy

              Comment


                #8
                Re: How to delete multiple rows at once

                Hi Andrew,

                All previous recommendations are pretty good and will work based on your particular need. In your case since the ContactID may be in many other related tables which should prevent the Parent ContactID record from being deleted, it is best to manually deal with this kind of deletion since the CASCADE option of the database will not do it for you.

                I use MS-SQL, so for this cases I have a Stored Procedure which will return the COUNT(*) of records in each related table then if this is greater than 0, the deletion of Parent record is not allowed.

                Here is a sample code of one of these Stored Procedures:
                Code:
                -- =============================================
                -- Author:		<Edhy Rijo>
                -- Create date: <7/18/2013>
                -- spRelatedRecordsCountForPK_Providers
                -- Description:	<Return the number of related records found for this Provider>
                -- =============================================
                ALTER PROCEDURE [dbo].[spRelatedRecordsCountForPK_Providers]
                
                @PK_Providers AS INT
                
                AS
                
                SELECT
                	COALESCE((SELECT COUNT(*) FROM ProvidersCalendar pc WHERE pc.FK_Providers = @PK_Providers), 0) +
                	COALESCE((SELECT COUNT(*) FROM Students s WHERE s.FK_Providers = @PK_Providers OR s.FK_Providers2 = @PK_Providers), 0) +
                	COALESCE((SELECT COUNT(*) FROM StudentsProvidersLink spl WHERE spl.FK_Providers = @PK_Providers), 0) +
                	COALESCE((SELECT COUNT(*) FROM Notes n WHERE n.FK_Providers = @PK_Providers), 0) AS RelatedRecordsCount
                Basically I am just counting the records in each related table using the Foreign Key value in PK_Providers. The COALESCE() function will simply return 0 if the result of the COUNT(*) is NULL.

                Then in the grid canDeleteRecord() function I have the following code:
                Code:
                function CanDeleteRecord as v (DataSubmitted as P, Args as p, PageVariables as p, Result as P)
                with PageVariables
                
                Result.Cancel = .f.
                Result.ErrorHTML = ""
                
                '-- Only allow delete of records if the Provider does not have any related record.
                dim conn as SQL::Connection
                dim sqlStmt as c
                dim rs as SQL::ResultSet	
                dim args as sql::Arguments
                args.add("PK_Providers", convert_type(DataSubmitted.PK_Providers, "N"))
                sqlSelect = "EXEC spRelatedRecordsCountForPK_Providers :PK_Providers"
                if conn.Open("::Name::BCI") then
                	if conn.execute(sqlSelect, Args) then
                		rs = conn.ResultSet
                		if rs.DataIsNull(1) = .f.
                			dim RelatedRecordsCount as N = convert_type(rs.data("RelatedRecordsCount"), "N")
                
                			'-- If there are related records for this Provider, then abort the deletion process.
                			if RelatedRecordsCount > 0 then
                				Result.Cancel = .T.
                				Result.ErrorHTML = "This provider cannot be deleted.  There are other related records using this Provider."
                			end if	
                		end if
                	end if
                	
                	'-- There are some memory leaks so be sure the connection is closed.
                	conn.close() 
                end if
                
                end with
                end function
                Hope this help.
                Edhy Rijo
                Progytech
                (Computer Consultants)
                The makers of CardTracking.Net
                www.progytech.com

                Comment

                Working...
                X