how to make condition to update table? - sql

i want to make condition to update my table if there's already same data (in the same column) inserted in the table.
im using
If String.ReferenceEquals(hotel, hotel) = False Then
insertDatabase()
Else
updateDatabase()
End If
this is the updateDatabase() code...
Dim sql2 As String = "update infoHotel set nameHotel = N" & FormatSqlParam(hotel) & _
", streetAddress = N" & FormatSqlParam(StreetAddress) & _
", locality = N" & FormatSqlParam(Locality) & _
", postalCode = N" & FormatSqlParam(PostalCode) & _
", country = N" & FormatSqlParam(Country) & _
", addressFull = N" & FormatSqlParam(address) & _
", tel = N" & FormatSqlParam(contact) & _
"where hotel = '" & hotel & "')"
this is the formatSqlParam() code:
Function FormatSqlParam(ByVal strParam As String) As String
Dim newParamFormat As String
If strParam = String.Empty Then
newParamFormat = "'" & "NA" & "'"
Else
newParamFormat = strParam.Trim()
newParamFormat = "'" & newParamFormat.Replace("'", "''") & "'"
End If
Return newParamFormat
End Function
the function manage to go into updateDatabase() but has some error saying
"Incorrect syntax near 'Oriental'."
Oriental is the data inserted in the table. is it suitable to use ReferenceEquals?
im using vb.net and sql database..tq

You should be using parameterized queries instead of concatenating strings like so:
Dim sql2 As String = "Update InfoHotel" _
& "Set nameHotel = #nameHotel" _
& ", knownAs1 = #knownAs1" _
& ", knownAs2 = #knownAs2" _
& ", knownAs3 = #knownAs3" _
& ", knownAs4 = #knownAs4" _
& " Where hotel = #hotel"
If you used parameterized queries, you wouldn't have to worry about trying do quote replacement and potentially introducing a SQL Injection vulnerability.

You have a single quote in your data, as in:
Oriental's
Show us the code for FormatSqlParam() -- the bug is probably in there.
Or else you left out the single quotes around the hotel name:
where hotel = '" & hotel & "')"
I hope that's not it, because it would mean you're using the name as a key, a very bad idea.

Related

SQL Query using VBA and ADO record set - Code takes far less time to execute when run the second time

I have a VBA Code that involves, among other things, looping of an SQL query written as a Function. When I run the code for the first time, it takes nearly 155 seconds(which is understandable given the complexity of the calculation), when I run it for the second time it takes about 19 seconds. I would like to know why? Also how can I make it run faster? The SQL server version is 2008.
FunctionX() below, is used subsequently in For and Do while Loops, so I understand that a new Connection is created every time it runs.
Option Explicit
Public
Public conn As Object 'connection
________________________________________
Sub CreateConnection ()
Set conn = CreateObject("ADODB.connection")
Dim connstring As String
connstring = "Driver={SQL Server};Server=172.20.1.172;Database=WindAccess_dat_MRK;Uid=MRK_user;Pwd=MRK010usr;"
conn.Open connstring
conn.CommandTimeout = 120
End Sub
____________________________________
FunctionX(ActiveConnection as Object, arg1,arg2,....)
Dim SQLqryfunc1 As String
Dim SQLqryfunc2 As String
Dim SQLqryfunc3 As String
Dim fValue As Variant
Set wb = ThisWorkbook
Dim recset As Object
Set recset = CreateObject("ADODB.Recordset")
Dim ItemString1 As String
Dim ItemString2 As String
Dim ItemString3 As String
Dim ItemString4 As String
Dim ItemString5 As String
Dim StartZeit As String
Dim EndZeit As String
Select Case ChooseZeit
Case 1
StartZeit = Format(InputDateErsterTag, "yyyy-mm-dd hh:mm:ss.000")
EndZeit = Format(InputDateLetzterTag, "yyyy-mm-dd 23:50:ss.000")
ItemString3 = " AND HAL150.WTUR_AVG.MaxPwrSetpoint >=" & MaxPwrSetpoint_AvgVal
ItemString4 = " AND HAL150.WTUR_MIN.MaxPwrSetpoint >=" & MaxPwrSetpoint_MinVal
ItemString5 = " AND HAL150.WTUR_AVG.W >=" & WAvg_Min
Case 2
StartZeit = Format(InputDateErsterTag, "yyyy-mm-dd hh:mm:ss.000")
EndZeit = Format(InputDateLetzterTag, "yyyy-mm-dd hh:mm:ss.000")
ItemString3 = ""
ItemString4 = ""
ItemString5 = ""
End Select
Select Case Item
Case 1 ' 1= m
ItemString1 = " count(case when WindSpeed_Avg"
ItemString2 = " then 1 end)"
Case 2 ' 2= p
ItemString1 = " sum(case when WindSpeed_Avg"
ItemString2 = " then Leistung_Avg end)"
End Select
SQLqryfunc1 = "SELECT" _
& ItemString1 _
& " >=" _
& myWindSpeedFrom _
& " and" _
& " WindSpeed_Avg" _
& " <" _
& myWindSpeedTo _
& ItemString2 _
& " as '13.48 bis 14'" _
SQLqryfunc2 = " from" _
& " (" _
& " SELECT Time_Stamp, LDName as MONr,HAL150.WTUR_AVG.W as Leistung_Avg," _
& " WdSpd as WindSpeed_Avg, HAL150.WTUR_AVG.MaxPwrSetpoint as MaxPwrSetpoint_Avg,HAL150.WTUR_MIN.MaxPwrSetpoint as MaxPwrSetpoint_Min" _
& " FROM WSKD.RegCtrPeriodBlock" _
& " INNER JOIN HAL150.WNAC_AVG " _
& " ON WSKD.RegCtrPeriodBlock.idPBlock = HAL150.WNAC_AVG.idPBlock" _
& " INNER JOIN HAL150.WTUR_AVG" _
& " ON WSKD.RegCtrPeriodBlock.idPBlock = HAL150.WTUR_AVG.idPBlock" _
& " INNER JOIN WSKD.Components" _
& " ON WSKD.RegCtrPeriodBlock.IdLD = WSKD.Components.IdLD" _
& " INNER JOIN HAL150.WTUR_MIN" _
& " ON WSKD.RegCtrPeriodBlock.idPBlock = HAL150.WTUR_MIN.idPBlock" _
& " WHERE Time_Stamp BETWEEN" _
& " '" & StartZeit & "'" _
& " AND" _
& " '" & EndZeit & "'" _
& " AND" _
& " LDName in" _
& " (" & "'" & MONr & "'" & ")" _
& ItemString3 _
& ItemString4 _
& ItemString5 _
& " )" _
& " tbl"
SQLqryfunc3 = SQLqryfunc1 & SQLqryfunc2
'Debug.Print SQLqryfunc3
recset.Open SQLqryfunc3, myActiveConnection
fValue = recset.Getrows
Functionx = fValue(0, 0)
'Debug.Print Functionx
End Function
The second time your queries are executed they are likely cached by SQL server.
Lowest hanging fruit to making your query faster would be to take a sample output from this function and run it through SQL Server Management Studio with execution plan enabled: https://learn.microsoft.com/en-us/sql/relational-databases/performance/display-an-actual-execution-plan?view=sql-server-ver15 . It'll give you some tips on what indexes could be added to certain columns to make your query faster. If you have create privileges on database you can create some indexes to speed things up a bit. You'll also be able to see which parts of your query are the most expensive.
Also, dynamic SQL is hard on SQL server precisely because it has to come up with a new optimized execution plan each time and isn't able to keep it for very long. The reason it slows down again is because the optimized execution plan it creates the first time is ejected from the cache. SQL concatenation like this & " WHERE Time_Stamp BETWEEN" _ & " '" & StartZeit & "'" _ also opens you up to SQL injection attacks if the input is from the user. So if you can use parameters in your query instead using ADODB much like in this example answer here: https://stackoverflow.com/a/10353908/4641232 it would make your code more secure.
Another idea to optimize your code might be to move the processing of conditionals onto SQL server. For example, this case here:
Select Case ChooseZeit
Case 1
StartZeit = Format(InputDateErsterTag, "yyyy-mm-dd hh:mm:ss.000")
EndZeit = Format(InputDateLetzterTag, "yyyy-mm-dd 23:50:ss.000")
ItemString3 = " AND HAL150.WTUR_AVG.MaxPwrSetpoint >=" & MaxPwrSetpoint_AvgVal
ItemString4 = " AND HAL150.WTUR_MIN.MaxPwrSetpoint >=" & MaxPwrSetpoint_MinVal
ItemString5 = " AND HAL150.WTUR_AVG.W >=" & WAvg_Min
Case 2
StartZeit = Format(InputDateErsterTag, "yyyy-mm-dd hh:mm:ss.000")
EndZeit = Format(InputDateLetzterTag, "yyyy-mm-dd hh:mm:ss.000")
ItemString3 = ""
ItemString4 = ""
ItemString5 = ""
End Select
Instead of having two possible WHERE clauses, have your VBA create a SQL script that includes both and have SQL server make the distinction. For example, the WHERE clause in your output might look like this:
...
WHERE
...
AND
(
(
2 = 1 -- ChooseZeit == 2 in VB so that's where the 2 comes from.
AND HAL150.WTUR_AVG.MaxPwrSetpoint >= 4 -- I just picked a random number here.
AND HAL150.WTUR_MIN.MaxPwrSetpoint >= 2 -- I just picked a random number here.
AND HAL150.WTUR_AVG.W >= 3 -- I just picked a random number here.
)
OR
(
2 = 2 -- ChooseZeit == 2 in VB so that's where the 2 comes from.
)
)
...
With your WHERE clause constructed this way you give SQL Server a constant query structure to build an optimized path. If you use parameters, you can also now more easily move the scripted query created by VB into a stored procedure that you can compile on SQL server to possibly give even more gains.

Combobox filtering for listbox output is not working as expected

I have a few controls (Combobox's I call DDL's) that I use as filters for a dynamic query, shown below.
I have a region, division filter - and BCI/BCV/ABC/etc dropdowns.
When I select the region and division, the output list box correctly filters out everything except THOSE region/divisions. Good.
The problem comes in when I use the other DDL's, ABD/BCI/etc... those do not filter out correctly and I think it is with my and/or clauses below.
Can anyone see anything glaring or point me in the right direction to get this so that every control and ddl element filters out the data it is intended for - while keeping it in a format where the SQL itself is part of a string, like in my example?
Private Sub goBtn_Click()
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs " & _
"WHERE DivisionDDL = [Division_Name] and RegionDDL = [Region_Name] " & _
" and ( [BCI_Ind] = CheckBCI.value or [BCV_Ind] = CheckBCV.value or [ABC_Ind] = CheckABC.value " & _
" or BCIServiceDDL = [Tier]" & _
" or BCVServiceDDL = [Description_2]" & _
" or ABCServiceDDL = [Unit_ID] )" & _
"ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
One of the combo box DDL control codes. There are check boxes that make the combo box visible or not visible.
Private Sub CheckBCV_Click()
If Me.CheckBCV = vbTrue Then
Me.BCVServiceDDL.Visible = True
Me.BCVServiceDDL = "Select:"
strSQL = "SELECT Distinct subs.[Description_2] FROM dbo_ndw_bc_subs "
Me.BCVServiceDDL.RowSource = strSQL
Me.BCVServiceDDL.Requery
Else
Me.BCVServiceDDL.Visible = False
Me.BCVServiceDDL = ""
End If
End Sub
Edit: Added additional code to the first code block for context, and updated some comments.
To reiterate the point of my question - Since some of the DDL's work as expected while the others do not. Is it in the AND/OR section where I have a problem - or am I forced to do an IF/IIF statement in the select. (And if I do this IF solution - how would that be incorporated into a string the way I have it now, I have not seen an example of this in my research on a resolution).
I think your top code sample should read more like this:
Private Sub goBtn_Click()
Dim strSQL As String
Dim strWhere As String
Dim strOp As String
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs "
strWhere = ""
strOp = ""
If Not IsNull(Me.DivisionDDL.Value) Then
strWhere = strWhere & strOp & "(Division_Name = """ & Me.DivisionDDL.Value & """)"
strOp = " And "
End If
If Not IsNull(Me.RegionDDL.Value) Then
strWhere = strWhere & strOp & "(Region_Name = """ & Me.RegionDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCI.Value Then
strWhere = strWhere & strOp & "(Tier = """ & Me.BCIServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCV.Value Then
strWhere = strWhere & strOp & "(Description_2 = """ & Me.BCVServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckABC.Value Then
strWhere = strWhere & strOp & "(Unit_ID = """ & Me.ABCServiceDDL.Value & """)"
strOp = " And "
End If
If Len(strWhere) > 0 then
strSQL = strSQL & " WHERE " & strWhere
End If
strSQL = strSQL & " ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
This is wordier, but much closer to correct. P.S. I guessed that all values are strings. If not remove the quoting around non-string values.

MS-Access Update SQL Not Null But is Blank (! Date & Number Fields !)

I have a few controls that are number and short date format in my tables also the date controls are masked to mm/dd/yyyy. Some of the fields that are loaded into the form are blank from the original table and so when executing the sql I am essentially evaluating the wrong thing whether Im checking for '' or Null. as '' fails as text for date number and the fields are not actually blank.
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = IIF(IsNull(" & Forms!frmEdit.txtProposed.Value & "),0," & Forms!frmEdit.txtProposed.Value & "), " & _
"[Multi] = IIF(IsNull(" & Forms!frmEdit.txtMulitplier.Value & "),0," & Forms!frmEdit.txtMulitplier.Value & "), " & _
"[Rational] = '" & Forms!frmEdit.txtRational.Value & "' " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Debug.Print strSQL4
dbs.Execute strSQL4
ERROR 3075 Wrong number of arguments used with function in query expression
'IIF(IsNull(),0,'
I also tried entering the field itself suggested from another site
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = IIF(" & Forms!frmEdit.txtProposed.Value & "='',[Proposed]," & Forms!frmEdit.txtProposed.Value & "), " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Debug.Print strSQL4
dbs.Execute strSQL4
Same Error 3075 'IIF(IsNull(),0,[ProposedHrs]'
***also fails if I use the IIF(IsNull method as opposed to the =''
I did not paste an example of the dates failing, but is the same idea, not null but is blank, but cant seem to update back to blank again or even skip maybe?
Thanks to anyone in advance.
Update-1 from attempting Erik Von Asmuth code <--Thanks btw!
Set qdf = db.CreateQueryDef("", & _
"UPDATE [tblDetails] SET " & _
"[Proposed] = #Proposed, " & _
"[Multi] = #Multi, " & _
"[Rational] = #Rational " & _
"WHERE [RNumber] = #RNumber")
This portion is all red and the first "&" is highlighted after closing the notification window
Compile error:
Expected: expression
Update-2: I moved the update to the first line and it seems to be working. Set qdf = db.CreateQueryDef("", "UPDATE [tblDetails] SET " & _
I am going to try this method with the dates fields next.
Update-3: when attempting the same parameterization with textbox's masked with 99/99/0000;0;_ I am receiving item not found in collection? I have checked the spelling several times and everything seems ok. I tried the following three formats so set parameter DateRcvd, can anyone comment if this is correct for a text box with dates?
qdf.Parameters("#DateRcvd") = IIf(Nz(Forms!frmEdit.txtDateRcvd.Value) = "", 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#DateRcvd") = IIf(IsNull(Forms!frmEdit.txtDateRcvd.Value), 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#DateRcvd") = IIf(Forms!frmEdit.txtDateRcvd.Value = "", 0, Forms!frmEdit.txtDateRcvd.Value)
Update-4:
Dim qdf2 As DAO.QueryDef
Set db = CurrentDb
Set qdf2 = db.CreateQueryDef("", "UPDATE [tblDetails] SET " & _
"[DateReceived] = #DateRcvd " & _
"WHERE [RNumber] = #RNumber")
qdf.Parameters("#DateRcvd") = IIf(Nz(Forms!frmEdit.txtDateRcvd.Value) = "", 0, Forms!frmEdit.txtDateRcvd.Value)
qdf.Parameters("#RNumber") = Forms!frmEdit.cmbUpdate.Value
qdf2.Execute
Please Note text box txtDateRcvd has an Input Mask 99/99/0000;0;_ set within the properties of the textbox.
You should account for empty strings, and do that IIF statement in VBA instead of SQL:
strSQL4 = "UPDATE [tblDetails] SET " & _
"[Proposed] = " & IIF(Nz(Forms!frmEdit.txtProposed.Value) = "",0, Forms!frmEdit.txtProposed.Value) & ", " & _
"[Multi] = " & IIF(Nz(Forms!frmEdit.txtMulitplier.Value) = "",0, Forms!frmEdit.txtMulitplier.Value) & ", " & _
"[Rational] = '" & Forms!frmEdit.txtRational.Value & "' " & _
" WHERE [RNumber] = '" & Forms!frmEdit.cmbUpdate.Value & "'"
Or better yet, do it properly and parameterize the whole update so you can't get these kind of errors or SQL injection.
Example of how to do it properly:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", _
"UPDATE [tblDetails] SET " & _
"[Proposed] = #Proposed, " & _
"[Multi] = #Multi, " & _
"[Rational] = #Rational " & _
"WHERE [RNumber] = #RNumber"
)
qdf.Parameters("#Proposed") = IIF(Nz(Forms!frmEdit.txtProposed.Value) = "",0, Forms!frmEdit.txtProposed.Value)
qdf.Parameters("#Multi") = IIF(Nz(Forms!frmEdit.txtMulitplier.Value) = "",0, Forms!frmEdit.txtMulitplier.Value)
qdf.Parameters("#Rational") = Forms!frmEdit.txtRational.Value
qdf.Parameters("#RNumber") = Forms!frmEdit.cmbUpdate.Value
qdf.Execute

item cannot be found in the collection corresponding to the requested name or ordinal

My code gives the following error. How can I correct this?
Item cannot be found in the collection corresponding to the requested name or ordinal
ElseIf Me.chkItem.Checked = True Then
Dim CheckNumber As String = ""
Dim CheckRef As String = ""
dsvoucheritem.Clear()
DSVoucher_Expense.Clear()
DSVoucher_Check.Clear()
Try
Me.lstCV.Items.Clear()
strDiscount = Nothing
rec.Open("select billpaymentcheckline.txnnumber, billpaymentcheckline.txndate" _
& ", billpaymentcheckline.payeeentityreffullname" _
& ", billpaymentcheckline.amount, billitemline.itemlineitemreffullname" _
& ", billitemline.memo" _
& ", billpaymentcheckline.appliedtotxndiscountamount" _
& ", billpaymentcheckline.appliedtotxnrefnumber, billpaymentcheckline.bankaccountreffullname" _
& ", billpaymentcheckline.appliedtotxndiscountaccountreffullname" _
& ", billpaymentcheckline.appliedtotxntxndate, billpaymentcheckline.appliedtotxnamount" _
& ", billpaymentcheckline.refnumber, account.AccountNumber from (billitemline inner join" _
& " billpaymentcheckline on billitemline.refnumber=billpaymentcheckline.appliedtotxnrefnumber) left outer join" _
& " account on billitemline.APAccountreflistid=account.listid where" _
& " billpaymentcheckline.bankaccountreflistid='" &Me.lblBankID.Text & "' and" _
& " billpaymentcheckline.refnumber between '" & CInt(Me.txtRefFR.Text)
& "' and '" & CInt(Me.txtRefTO.Text) & "'", con, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly)
It's saying it doesn't recognize one of your column names. Double check all of them. You can also try removing fields until you find the culprit.
memo is a reserved word in Access SQL.
Try billitemline.[memo]

i got sql syntax error when i debug my application

I want to update my database using formatsqlparam, but when I debug it, it has an error saying:
"Incorrect syntax near ','."
This is my code:
Dim sql2 As String = "update infoHotel set nameHotel = N" & FormatSqlParam(hotel) & _
", knownAs1 = N" & FormatSqlParam(KnownAs(0)) & _
", knownAs2 = N" & FormatSqlParam(KnownAs(1)) & _
", knownAs3 = N" & FormatSqlParam(KnownAs(2)) & _
", knownAs4 = N" & FormatSqlParam(KnownAs(3)) & _
", streetAddress = N" & FormatSqlParam(StreetAddress) & _
", locality = N" & FormatSqlParam(Locality) & _
", postalCode = N" & FormatSqlParam(PostalCode) & _
", country = N" & FormatSqlParam(Country) & _
", addressFull = N" & FormatSqlParam(address) & _
", tel = N" & FormatSqlParam(contact) & ","
Dim objCommand3 As New SqlCommand(sql2, conn)
objCommand3.ExecuteNonQuery()
Maybe I am missing some syntax, but I couldn't find where it is. I hope somebody can help. Thanks in advance. I'm using VB.Net and SQL.
The last line should be like this:
", tel = N" & FormatSqlParam(contact)
Also, you don't have a Where clause in your statement so this will update all rows in your table.
Looks like the trailing comma is your problem:
", tel = N" & FormatSqlParam(contact) & ","