473,395 Members | 1,681 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Replace Field Name with Variable (SQL)

106 100+
in my current procedure, I have string variable 'ConfirmRate',
in my sql section shown below, I need to replace the VATrate (select section) with ConfirmRate, I don't know how to do that.
your help is appreciated.
Expand|Select|Wrap|Line Numbers
  1. If Me.[ExtraDetailssub].Form.RecordsetClone.RecordCount > 0 Then
  2.   strSql = "INSERT INTO [Extras] ( PH_DetailsID, ExtraAmt, ItemDetails, VATyesno, VATrate ) " & _
  3.   "SELECT " & lngID & " As NewID, ExtraAmt, ItemDetails, VATyesno, VATrate " & _
  4.  "FROM [Extras] WHERE PH_DetailsID = " & Me.PH_DetailsId & ";"
  5.                 DBEngine(0)(0).Execute strSql, dbFailOnError
Aug 27 '09 #1

✓ answered by ADezii

The way the current Logic is structured, it appears as though you may need 2 independent events to accomplish what you are requesting, An Append to the Sub-Form (Extras) then an Update to same. See if this does the trick. Add Lines 7, 8, and 9 to this code segment in ReserveDup().
Expand|Select|Wrap|Line Numbers
  1. If Me.[ExtraDetailssub].Form.RecordsetClone.RecordCount > 0 Then
  2.   strSql = "INSERT INTO [Extras] ( PH_DetailsID, ExtraAmt, ItemDetails, VATyesno, VATrate ) " & _
  3.            "SELECT " & lngID & " As NewID, ExtraAmt, ItemDetails, VATyesno, VATrate " & _
  4.            "FROM [Extras] WHERE PH_DetailsID = " & Me.PH_DetailsId & ";"
  5.               DBEngine(0)(0).Execute strSql, dbFailOnError
  6.  
  7.               DBEngine(0)(0).Execute "UPDATE [Extras] SET [VATrate] = " & ConfirmRate & _
  8.                                      " WHERE [PH_DetailsID] = " & DLast("[PH_DetailsID]", _
  9.                                      "[Private_Hire_Detail]") & " AND [VATyesno] = True;", dbFailOnError
  10. Else
  11.   'MsgBox "Main record duplicated, but there were no related records."
  12. End If

15 7699
ajalwaysus
266 Expert 100+
I think you need to be more specific, I'm not sure what your problem is, my first reaction would be to try this:

Expand|Select|Wrap|Line Numbers
  1. If Me.[ExtraDetailssub].Form.RecordsetClone.RecordCount > 0 Then
  2. strSql = "INSERT INTO [Extras] ( PH_DetailsID, ExtraAmt, ItemDetails, VATyesno, VATrate ) " & _
  3. "SELECT " & lngID & " As NewID, ExtraAmt, ItemDetails, VATyesno, " & ConfirmRate & " FROM [Extras] WHERE PH_DetailsID = " & Me.PH_DetailsId & ";"
  4.  
  5. DBEngine(0)(0).Execute strSql, dbFailOnError 
  6.  
But from looking at your code, you seem like you would know that, so if I am wrong please post more information.

-AJ
Aug 27 '09 #2
tasawer
106 100+
Thank you AJ for your prompt response. You are working along the lines I am expecting. I tired the modification but it did not work.

In my fully working application, when an order is created, VATrate is applied to it according to the date period it was created.
if at a later date, the same customer repeats the order, I simpy duplicate it, including the VAT rate.
However, recently in the UK, there have been some VAT changes.
so now I wish to duplicate the order but apply the VAT rate applicable on the date period of duplication. current vat rate is 'ConfirmRate'

I hope I have explained myself better this time.
Aug 27 '09 #3
NeoPa
32,556 Expert Mod 16PB
AJ's response seems fine to me, assuming a numeric value is required.

Otherwise, please state which type of variable is required.

If this is not the problem perhaps you can post the relevant extract of the code that you've tried but have found to fail. I can only assume it's something else causing the problem.

Please include a clear explanation of any error.
Aug 29 '09 #4
ADezii
8,834 Expert 8TB
Unless I am reading this all wrong, which is very probable (LOL), you are trying to substitute an actual Value contained in the Variable ConfirmRate to a Field Descriptor in the Select Clause. If I am correct, then I imagine that this has to be a 2-Stage process, as in:
I have string variable 'ConfirmRate', in my sql section shown below
Expand|Select|Wrap|Line Numbers
  1. Dim strSQL As String
  2. Dim strSQL2 As String
  3.  
  4. strSQL = "INSERT INTO [Extras] ( PH_DetailsID, ExtraAmt, ItemDetails, VATyesno, VATrate ) " & _
  5.          "SELECT " & lngID & " As NewID, ExtraAmt, ItemDetails, VATyesno, VATrate " & _
  6.          "FROM [Extras] WHERE PH_DetailsID = " & Me.PH_DetailsId & ";"
  7.             DBEngine(0)(0).Execute strSQL, dbFailOnError
  8.  
  9.           'If ConfirmRate is a String, as you indicated in Initial Post
  10. strSQL2 = "Update [Extras] Set [VATrate] = '" & ConfirmRate & "' Where [lngID] = " & _
  11.            DLast("[lngID]", "[Extras]") & ";"
  12.  
  13.           'If ConfirmRate is Numeric
  14. strSQL2 = "Update [Extras] Set [VATrate] = " & ConfirmRate & " Where [lngID] = " & _
  15.            DLast("[lngID]", "[Extras]") & ";"
  16.              DBEngine(0)(0).Execute strSQL2, dbFailOnError
Aug 29 '09 #5
tasawer
106 100+
Hello Adezii, you have understood correctly.

I have tried both options above, Record gets duplicated but I get the error '2001 - You cancelled previous operation' (VATRate never gets updated though).

here is the full Function. (It basically copies the main record and the sub-records) - Main record gets the new vat rate but the sub records don't.

Thanks in advance to all willing to help.
Expand|Select|Wrap|Line Numbers
  1. Private Sub ReserveDup()
  2.  
  3. 'Purpose:   Duplicate the main form record and related records in the subform.
  4.     Dim strSql As String    'SQL statement.
  5.     Dim strSql2 As String   'SQL statment for VAT
  6.     Dim lngID As Long       'Primary key value of the new record.
  7.     Dim ThisWeek As Integer 'current week of hire
  8.     Dim LastDate As Date    'Last Date of Hire
  9.     Dim DaysDiff As Long    'Period of Each Hire
  10.     Dim ConfirmRate As Double 'Confirmed VATRate
  11.  
  12.     'Save and edits first
  13.     If Me.Dirty Then
  14.         Me.Dirty = False
  15.     End If
  16.  
  17.     'Make sure there is a record to duplicate.
  18.     If Me.NewRecord Then
  19.         MsgBox "Select the record to duplicate."
  20.     Else
  21.         'Duplicate the main record: add to form's clone.
  22.         With Me.RecordsetClone
  23.             .AddNew
  24.  
  25. ThisWeek = DMax("Week", "QryWeek") + 1
  26. LastDate = DMax("ToDate", "QryWeek") + 1
  27. DaysDiff = DateDiff("d", Me.FromDate, Me.ToDate)
  28. 'MsgBox (DaysDiff)
  29.  
  30.                 !HireId = Me.HireId
  31.                 !Week = ThisWeek
  32.                 !FromDate = LastDate
  33.                 !ToDate = LastDate + DaysDiff
  34.                 !HireCharge = Me.HireCharge
  35.                 !ContactID = Me.ContactID
  36.                 !OtherCharges = Me.OtherCharges
  37.                 Call VATRateCheck(LastDate, LastDate + DaysDiff, ConfirmRate)
  38.                 !VATrate = ConfirmRate
  39.                 '!VATrate = Me.VATrate
  40.                 '!VATamt = Me.VATamt
  41.  
  42. 'MsgBox "updatetime"
  43.                 'etc for other fields.
  44.             .Update
  45.  
  46.     'Save the primary key value, to use as the foreign key for the related records.
  47.             .Bookmark = .LastModified
  48.             lngID = !PH_DetailsId
  49.  
  50.             'Duplicate the related records: append query.
  51.             If Me.[ExtraDetailssub].Form.RecordsetClone.RecordCount > 0 Then
  52.                 strSql = "INSERT INTO [Extras] ( PH_DetailsID, ExtraAmt, ItemDetails, VATyesno, VATrate ) " & _
  53.                     "SELECT " & lngID & " As NewID, ExtraAmt, ItemDetails, VATyesno, VATrate " & _
  54.                     "FROM [Extras] WHERE PH_DetailsID = " & Me.PH_DetailsId & ";"
  55.                 DBEngine(0)(0).Execute strSql, dbFailOnError
  56.  
  57.             Else
  58.                 'MsgBox "Main record duplicated, but there were no related records."
  59.             End If
  60.  
  61.             'Display the new duplicate.
  62.             Me.Bookmark = .LastModified
  63.         End With
  64.     End If
  65.  
  66. Forms!Private_Hire_Charges.Refresh
  67. Forms!Private_Hire.Refresh
  68.  
  69. End Sub
Sep 1 '09 #6
ADezii
8,834 Expert 8TB
I have added Code Tags and did a little reformatting. Will look at this closer tomorrow.
Expand|Select|Wrap|Line Numbers
  1. Private Sub ReserveDup()
  2. 'Purpose: Duplicate the main form record and related records in the subform.
  3. Dim strSql As String        'SQL statement.
  4. Dim strSql2 As String       'SQL statment for VAT
  5. Dim lngID As Long           'Primary key value of the new record.
  6. Dim ThisWeek As Integer     'current week of hire
  7. Dim LastDate As Date        'Last Date of Hire
  8. Dim DaysDiff As Long        'Period of Each Hire
  9. Dim ConfirmRate As Double   'Confirmed VATRate
  10.  
  11. 'Save and edits first
  12. If Me.Dirty Then Me.Dirty = False
  13.  
  14. 'Make sure there is a record to duplicate.
  15. If Me.NewRecord Then
  16.   MsgBox "Select the record to duplicate."
  17. Else
  18.   'Duplicate the main record: add to form's clone.
  19.   With Me.RecordsetClone
  20.    .AddNew
  21.      ThisWeek = DMax("Week", "QryWeek") + 1
  22.      LastDate = DMax("ToDate", "QryWeek") + 1
  23.      DaysDiff = DateDiff("d", Me.FromDate, Me.ToDate)
  24.  
  25.      !HireId = Me.HireId
  26.      !Week = ThisWeek
  27.      !FromDate = LastDate
  28.      !ToDate = LastDate + DaysDiff
  29.      !HireCharge = Me.HireCharge
  30.      !ContactID = Me.ContactID
  31.      !OtherCharges = Me.OtherCharges
  32.        Call VATRateCheck(LastDate, LastDate + DaysDiff, ConfirmRate)
  33.      !VATrate = ConfirmRate
  34.    .Update
  35.  
  36.      'Save the primary key value, to use as the foreign key for the related records.
  37.    .Bookmark = .LastModified
  38.      lngID = !PH_DetailsId
  39.  
  40.     'Duplicate the related records: append query.
  41.     If Me.[ExtraDetailssub].Form.RecordsetClone.RecordCount > 0 Then
  42.       strSql = "INSERT INTO [Extras] ( PH_DetailsID, ExtraAmt, ItemDetails, VATyesno, VATrate ) " & _
  43.                "SELECT " & lngID & " As NewID, ExtraAmt, ItemDetails, VATyesno, VATrate " & _
  44.                "FROM [Extras] WHERE PH_DetailsID = " & Me.PH_DetailsId & ";"
  45.         DBEngine(0)(0).Execute strSql, dbFailOnError
  46.  
  47.     Else
  48.     End If
  49.  
  50.       'Display the new duplicate.
  51.       Me.Bookmark = .LastModified
  52.   End With
  53. End If
  54.  
  55. Forms!Private_Hire_Charges.Refresh
  56. Forms!Private_Hire.Refresh
  57. End Sub
Sep 2 '09 #7
ADezii
8,834 Expert 8TB
A couple of items stick right out:
  1. An Exit Sub should be placed between Lines 16 and 17, since there is no need to have the code fall through and process the Refresh Statements after Line #54 in Post #7.
  2. Is the [Week] Field declared as an Integer, since the ThisWeek Variable is defined as such in Line #6 of Post #7.
  3. Is the [ToDate] Field declared as a Date, since the LastDate Variable is defined as such in Line #7 of Post #7.
  4. What exactly does the VATRateCheck() Sub-Routine do? You are passing this Routine 2 Dates and a Double. Are the Sub-Routine Parameters an exact match as far as Data Types?
  5. ConfirmRate is declared in Line #9 but never initialized, yet it is passed (having no Value) to VATRateCheck() in Line #32 of Post #7, and then assigned to !VATRate in Line #33 where it again has no value.
Sep 2 '09 #8
tasawer
106 100+
1. I could move the refresh statements above the end if Lines #53 post #7
2. Week is defined as Long Integer
3. TODate is Date/Time Data type
4. VATRATEcheck checks the VAT rate applicable between two dates -
Expand|Select|Wrap|Line Numbers
  1. Public Function VATRateCheck(StartDate, EndDate, ConfirmRate)
  2.  
  3. Dim Rate1 As String
  4. Dim Rate2 As String
  5. Dim dt As String
  6. Dim df As String
  7.  
  8.     df = Month(StartDate) & "/" & Day(StartDate) & "/" & Year(StartDate)
  9.     dt = Month(EndDate) & "/" & Day(EndDate) & "/" & Year(EndDate)
  10.  
  11.     Rate1 = 0
  12.     Rate2 = 0
  13.  
  14. 'MsgBox df & " " & dt
  15.  
  16.     Rate1 = DLookup("vatrate", "tvatrate", _
  17.     "RateDateStart <= #" & df & "#" & " And RateDateEnd >= #" & df & "#")
  18.  
  19.     Rate2 = DLookup("vatrate", "tvatrate", _
  20.     "RateDateStart <= #" & dt & "#" & " And RateDateEnd >= #" & dt & "#")
  21.  
  22. 'MsgBox Rate1 & " " & Rate2
  23.  
  24.     If Rate1 <> Rate2 Then
  25.         MsgBox "VAT RATE CHANGES DURING THIS WEEK"
  26.         ConfirmRate = 0
  27.         Else
  28.         ConfirmRate = Rate1
  29.         End If
  30.  
  31. End Function
5. I reading the CONFIRMRATE value back from the function VATRATECHECK

As you can see, I am duplicating a record with subrecords.
when a customers hires equipment between two dates, I manually enter all the items.
when the same customers returns at a later date and hires exactly the same equipement again, I simply duplicate.
Since the VAT rate changes (01/12/08) (and another one this year), when I duplicate I am carryiing over the old vat rate.
with my coding, above, main record take the new vat, subrecords do not.
I believe a change to line #43 post #7 is required.

I am wondering if I should add an SQL statment 'INSERT INTO' to the newly created record and change the vat value.
what is your suggestion?
Sep 5 '09 #9
ADezii
8,834 Expert 8TB
In the initial Post you indicate ConfirmRate is a String, then it is Declared Locally as a Double. It is then passed to a Public Function where this Parameter (placeholder) is a Variant. You 'Call' this Function which negates the entire purpose of a Return Value from a Function. Instead of the Function itself returning the Value of ConfirmRate by assignment (=), its value is sent back as an Argument. I imagine that this logic is only part of the problem, if not now then in the future. The only suggestion that I can make is that if you are willing to send me the Database to my Private E-Mail Address, I'll have a look at it when I get a chance. Other than that, I am basically dead in the water. Let me know either way.

P.S. - What Version of Access are you using?
Sep 5 '09 #10
NeoPa
32,556 Expert Mod 16PB
Tasawer,

It seems you missed my edit comment requesting you use the [ CODE ] tags when you post code.

Please make sure you read this, and use the tags in all such posts in future.
Sep 5 '09 #11
tasawer
106 100+
to Adezzi, thanks for offering to look at my database. (post #10)
I have been to private messages but donot see a link for attachments. How do I send the file to yourself only please.
Sep 8 '09 #12
ADezii
8,834 Expert 8TB
@tasawer
I'll send you a Private Message (PM) with my E-Mail Address in it. Send it to that Address as an Attachment.
Sep 8 '09 #13
ADezii
8,834 Expert 8TB
The way the current Logic is structured, it appears as though you may need 2 independent events to accomplish what you are requesting, An Append to the Sub-Form (Extras) then an Update to same. See if this does the trick. Add Lines 7, 8, and 9 to this code segment in ReserveDup().
Expand|Select|Wrap|Line Numbers
  1. If Me.[ExtraDetailssub].Form.RecordsetClone.RecordCount > 0 Then
  2.   strSql = "INSERT INTO [Extras] ( PH_DetailsID, ExtraAmt, ItemDetails, VATyesno, VATrate ) " & _
  3.            "SELECT " & lngID & " As NewID, ExtraAmt, ItemDetails, VATyesno, VATrate " & _
  4.            "FROM [Extras] WHERE PH_DetailsID = " & Me.PH_DetailsId & ";"
  5.               DBEngine(0)(0).Execute strSql, dbFailOnError
  6.  
  7.               DBEngine(0)(0).Execute "UPDATE [Extras] SET [VATrate] = " & ConfirmRate & _
  8.                                      " WHERE [PH_DetailsID] = " & DLast("[PH_DetailsID]", _
  9.                                      "[Private_Hire_Detail]") & " AND [VATyesno] = True;", dbFailOnError
  10. Else
  11.   'MsgBox "Main record duplicated, but there were no related records."
  12. End If
Sep 8 '09 #14
tasawer
106 100+
Fantastic.. that works wonderfully. Thanks a million.
Now What about the double clicking to create new record.
Sep 8 '09 #15
ADezii
8,834 Expert 8TB
@tasawer
Fantastic.. that works wonderfully. Thanks a million.
You are quite welcome. If you look back at Post #5, you'll see that we were on the right track - just lacked the specifics.
What about the double clicking to create new record.
Did not happen for me.
Sep 8 '09 #16

Sign in to post your reply or Sign up for a free account.

Similar topics

20
by: | last post by:
If I need to check if a certain value does exist in a field, and return either "yes" or "not" which query would be the most effestive?
7
by: Consuelo Guenther | last post by:
Hello, I have an asp page that has a function that connects to an Access database. I am using Javascript. Is there any way to reference the field name in the database through a variable in a sql...
2
by: ~TheIcemanCometh~ | last post by:
I have 2 questions. I am trying to write a stored procedure to update a table. I am trying to pass a variable that represents the name of the column/field and another for the value that I am...
8
by: Peter van Schie | last post by:
Hi all, Give an xml document that looks something like this: <?xml version="1.0" encoding="iso-8859-1"?> <?xml-stylesheet type="text/xsl"...
5
by: Colleyville Alan | last post by:
I have built a SQL statement that is trying to loop through the fields of a table that was built from a spreadsheet and hence is "short and fat". So rather than hard-coding, I have a loop from...
3
by: John young | last post by:
I have been looking for an answer to a problem and have found this group and hope you can assist . I have been re doing a data base I have made for a car club I am with and have been trying to...
4
by: serge | last post by:
I managed to put together C# code and have it do the following: 1- Get all the table names that start with the letter "Z" from sysobjects of my SQL 2000 database and put these table names...
52
by: MP | last post by:
Hi trying to begin to learn database using vb6, ado/adox, mdb format, sql (not using access...just mdb format via ado) i need to group the values of multiple fields - get their possible...
3
by: Hvid Hat | last post by:
Hi I want to highlight (make it bold) a word in some text I'm getting in XML format. My plan was to replace the word with a bold (or span) tag with the word within the tag. I've found the code...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.