Insert NULL value into SQL Server from Classic ASP - sql-server

I am trying to do a simple insert or update into SQL Server as NULL, not blank. I have seen many references online to just set Field = NULL without quotes but it is still coming up as empty, not NULL. Incredibly frustrating.
This is in classic asp.
If Request.Form("Field") = "" or IsNull(Request.Form("Field")) then
Field = NULL
Else
Field = Request.Form("Field")
End If
sSql="UPDATE [table] SET timestamp = {fn NOW()}," &_
"Field = '" & Field & "'," &_
"WHERE [System] = '" & System & "' and Active = '1'"
If I do this, it proves that it is checking because it puts in a 1.
If Request.Form("Field") = "" or IsNull(Request.Form("Field")) then
Field = 1
Else
Field = Request.Form("Field")
End If
sSql="UPDATE [table] SET timestamp = {fn NOW()}," &_
"Field = '" & Field & "'," &_
"WHERE [System] = '" & System & "' and Active = '1'"
I tried this but get an error 500:
sSql="UPDATE [Table] SET timestamp = {fn NOW()}, Field = "
If IsNull(Field) Then
sSQL = sSQL & "NULL"
Else
sSQL = sSQL & "'" & Field & "'" &_
End If
"NTLogon = '" & UCase(NTLogon) & "'" &_
"WHERE [System] = '" & System & "' and Active = '1'"
When I try this in place of my original code:
Field Assignment:
Field = "NULL" and Field = "'" & Request.Form("Field") & "'"
sSQL:
"Field = " & Field & "," &_
I get "An error occurred on the server when processing the URL."

So yeah, insert rant here about using parameterized queries, blah blah blah... now that's out of everyone's system, could we maybe look at the actual question?
The problem is this:
"Field = '" & Field & "'"
Those ampersands are converting your lovingly-populated vbScript NULL value right back into a string. If you don't want that to happen, you need to explicitly handle the IsNull case.
sSQL = "UPDATE [table] SET timestamp = {fn NOW()}, Field = "
If IsNull(Field) Then
sSQL = sSQL & "NULL"
Else
sSQL = sSQL & "'" & Field & "'"
End If
sSQL = sSQL & " WHERE [System] = '" & System & "' AND Active = '1'"
Note that even if you do this via a parameterized query, you'll need to make sure you're not appending your vbScript NULL value onto a string, because "" & NULL = "".

#pinchetpooche Hello there. I had the same issue and tried the given answer, and also received a 500 error page. I found that #Martha forgot to include the necessary SQL field that is being updated (i.e., "Field"). So I put together some test code, using her solution (i.e., using string concatenation and conditional logic), and executed against an actual database, and this solution works perfectly:
sSQLNullTest = "UPDATE CustomersToCCData SET "
sSQLNullTest = sSQLNullTest & "CustomerID = " & iCustomerID & ", "
If IsNull(x_license_number_state) Or x_license_number_state = "" Then
sSQLNullTest = sSQLNullTest & "CCLicenseState = NULL"
Else
sSQLNullTest = sSQLNullTest & "CCLicenseState = '" & x_license_number_state & "' "
End If
sSQLNullTest = sSQLNullTest & " WHERE CCID = '" & iCCInfoCCID & "'

Related

Docmd.RunSql Run-time error '3464' - update query

I am trying to update access table using simple VBA code, however it finished with an error. I have tried various ways to solve it but without success.
Could you please help? The code is as follow:
strSQL = "UPDATE Projects " & _
"SET Projects.id_status = '" & Me.T_project_s.Value & "' " & _
"WHERE Projects.id_project = '" & Me.curr_open.Value & "';"
I have also tried:
strSQL = "UPDATE Projects " & _
"SET Projects.id_status = [" & Me.T_project_s.Value & "] " & _
"WHERE Projects.id_project = [" & Me.curr_open.Value & "];"
or
strSQL = "UPDATE [Projects] " & _
"SET [Projects].[id_status] = '" & Me.T_project_s.Value & "' " & _
"WHERE [Projects].[id_project] = '" & Me.curr_open.Value & "';"
But it asks for a data which is available in those fields.
Your suggestion helped. I started with only a text then I have changed particular variables I wanted to be read. So in the Where statement there is no need to have beside "" also '' :).
strSQL = "UPDATE [Projects] " & _
"SET [Projects].[id_status] = '" & Me.T_project_s.Value & "' " & _
"WHERE [Projects].[id_project] = " & Me.curr_open.Value & ";"
Thanks.
Once again, here is an example where parameterization (an industry best practice in SQL programming) helps beyond avoiding SQL injection. With querydef parameters you:
avoid the need of quote enclosure;
avoid string interpolation of variables;
abstract data (i.e., VBA variables) from code (i.e., SQL statement) for cleaner scripts;
(plus as OP found out with mixed types) explicitly define the data types of values to be binded;
execute the query via DAO for smoother user interface than DoCmd.RunSQL that raises warnings to users.
Temp Query
Dim qdef As QueryDef
' PREPARED STATEMENT, DEFINING PLACEHOLDERS (NO DATA)
strSQL = "PARAMETERS [project_s_param] Text(255), [curr_open_param] Long;" & _
" UPDATE [Projects]" & _
" SET [Projects].[id_status] = [project_s_param]" & _
" WHERE [Projects].[id_project] = [curr_open_param];"
' CREATE UNNAMED TEMP QUERYDEF, ASSIGNING PREPARED STATEMENT
Set qdef = CurrentDb.CreateQueryDef("", strSQL)
' BIND VBA VALUES TO PARAMETER PLACEHOLDERS
qdef![project_s_param] = Me.T_project_s.Value
qdef![curr_open_param] = Me.curr_open.Value
' EXECUTE ACTION
qdef.Execute dbFailOnError
Set qdef = Nothing
Saved Query
Even better, save entire prepared statement as a stored Access query and avoid any SQL in VBA.
SQL (save as any regular query object whose name is referenced in VBA)
PARAMETERS [project_s_param] Text(255), [curr_open_param] Long;
UPDATE [Projects]
SET [Projects].[id_status] = [project_s_param]
WHERE [Projects].[id_project] = [curr_open_param]
VBA
Dim qdef As QueryDef
' REFERENCE EXISTING QUERYDEF, ASSIGNING PREPARED STATEMENT
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
' BIND VBA VALUES TO PARAMETER PLACEHOLDERS
qdef![project_s_param] = Me.T_project_s.Value
qdef![curr_open_param] = Me.curr_open.Value
' EXECUTE ACTION
qdef.Execute dbFailOnError
Set qdef = Nothing

Multiple If condition using Microsoft Access database in VB Net

I am trying to make a banking system where the customer will only be able to deposit money IF ONLY they enter the CORRECT AccountNo & Name using Microsoft Access Databse in VB NET.
Here are my codes:
Dim conn As New OleDbConnection
Dim conn = "provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Database\Bank-Application-Database.accdb;"
conn.ConnectionString = "provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Database\Bank-Application-Database.accdb;"
cmdupdate.Connection = cnnOLEDB
Dim deposit As OleDbCommand = New OleDbCommand("SELECT * FROM [Current_Account] WHERE [AccountNo] and [CustomerName] = '" & accnotxt.Text & "' AND [CustomerName] = '" & nametxt.Text & "' AND [Amount] = '" & amounttxt.Text & "'", myConnection)
deposit.Connection = conn
conn.Open()
If accnotxt.ToString = True And nametxt.ToString = True Then
cmdupdate.CommandText = "UPDATE [Current_Account] SET [Amount] = '" & amounttxt.Text.ToString & " WHERE [AccountNo] AND [CustomerName] = " & accnotxt.Text.ToString & " " & nametxt.ToString & ";"
cmdupdate.CommandType = CommandType.Text
cmdupdate.ExecuteNonQuery()
MsgBox(" Successfully deposited.")
Else
MsgBox("Incorrect Account Number or Name.")
I am able to run.However when I click to Deposit, this is the error.
The error I got:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "System.Windows.Forms.TextBox, Te" to type 'Boolean' is not valid.
Any helpers ? Thanks in advance.
In addition to #Jonathon Ogden's answer:
You missed your single quotes in this query:
cmdupdate.CommandText = "UPDATE [Current_Account] SET [Amount] = '" & amounttxt.Text.ToString & " WHERE [AccountNo] AND [CustomerName] = " & accnotxt.Text.ToString & " " & nametxt.ToString & ";"
Change it to this:
cmdupdate.CommandText = "UPDATE [Current_Account] SET [Amount] = " & Val(amounttxt.Text) & " WHERE [AccountNo]= '" & accnotxt.Text & "' AND [CustomerName] = '" & nametxt.Text & "';"
I also removed there the single quote from amounttxt.Text.ToString assuming it's a value, changed it to Val(amounttxt.Text) so that even that textbox is blank, it won't cause an error.
Also corrected your WHERE Condition:
Another is you don't need .ToString anymore since .Text property is already a String.
Your ToString usage will convert the value of the accnotxt and nametxt text boxes into a text string and you're trying to compare that to True (i.e. accnotxt.ToString = True) which is of a Boolean data type not a String data type i.e. you are trying to compare text to a boolean (true or false) value.
A very basic way (that can be improved on) of doing the account number and name check would be to change your SELECT statement to:
Dim deposit As OleDbCommand = New OleDbCommand("SELECT * FROM [Current_Account] WHERE [AccountNo] and [CustomerName] = '" & accnotxt.Text & "' AND [CustomerName] = '" & nametxt.Text & "'", myConnection)
I removed the Amount filter from the WHERE clause as I am not sure why you are doing that. You don't even use this deposit database command. You then execute the deposit SQL command and get its result: Dim result = deposit.ExecuteScalar(). ExecuteScalar does the following:
Executes the query, and returns the first column of the first row in the result set returned by the query.
You then change your account number and name check to If result IsNot Nothing Then instead of checking if the values of the textboxes are a particular account number and name.
In other words, if your query returns something and not nothing, then you can assume a current account exists with the accnotxt and nametxt.
Also, pay attention to #CrushSundae answer as they have highlighted other issues too.

Ms Access VBa where condition with (And) Error

i have a problem or lets say an error i get
i'm having that "Run Time-error '13' type mismatch" error when running this code
DoCmd.OpenReport "hamw_m3amala_naw_w_mawad", acViewReport, , "Jori_Mawad = '" & Combo14 & "' " And "ID =" & Combo4
note that Jori_Mawad is String and ID is Number
and that this two condition without the (And) do not have any problem and works fine :
DoCmd.OpenReport "hamw_m3amala_naw_w_mawad", acViewReport, , "Jori_Mawad = '" & Combo14 & "'"
DoCmd.OpenReport "hamw_m3amala_naw_w_mawad", acViewReport, , "ID = " & Combo4
Your
And
should be within the string that you are using as a where clause, but you are instead And-ing the first part of your clause with the second.
try
"Jori_Mawad = '" & Combo14 & "' And ID =" & Combo4

Overwrite value in DB with a NULL using VBA

If cell.Value <> "" Then
uid = cell
lname = Left(Replace(Range(cell.Address).Offset(0, 1), "'", ""), 50)
fname = Replace(Range(cell.Address).Offset(0, 2), "'", "")
stat = Replace(Range(cell.Address).Offset(0, 3), "'", "")
role = Left(Replace(Range(cell.Address).Offset(0, 4), "'", ""), 50)
iqn = Replace(Range(cell.Address).Offset(0, 5), "'", "")
sdate = Format(Replace(Range(cell.Address).Offset(0, 6), "'", ""), "yyyy-mm-dd")
bdate = Format(Replace(Range(cell.Address).Offset(0, 7), "'", ""), "yyyy-mm-dd")
rodate = Format(Replace(Range(cell.Address).Offset(0, 8), "'", ""), "yyyy-mm-dd")
End If
hirereason = Replace(Range(cell.Address).Offset(0, 9), "'", "")
roreason = Replace(Range(cell.Address).Offset(0, 10), "'", "")
sql = "BEGIN TRAN IF EXISTS (SELECT * FROM " & TableName & " WITH (updlock, serializable)"
sql = sql & " WHERE UID = '" & uid & "')"
sql = sql & " BEGIN"
sql = sql & " UPDATE" & TableName
sql = sql & " SET LName='" & lname & "', FName='" & fname & "'"
sql = sql & ", Status='" & stat & "', Role='" & role & "'"
sql = sql & ", IQNRole='" & iqn & "', StartDate='" & sdate & "'"
sql = sql & ", BillableDate='" & bdate & "', RollOffDate='" & rodate & "'"
sql = sql & ", HireReason='" & hirereason & "', RollOffReason='" & roreason & "'"
sql = sql & " WHERE UID = '" & uid & "'"
sql = sql & " END"
sql = sql & " ELSE BEGIN"
sql = sql & " INSERT " & TableName & " (UID, LName, FName, Status, Role, IQNRole, StartDate"
sql = sql & ", BillableDate, RollOffDate, HireReason, RollOffReason)"
sql = sql & " VALUES('" & uid & "', '" & lname & "', '" & fname & "', '" & stat & "'"
sql = sql & ", '" & role & "', '" & iqn & "', '" & sdate & "', '" & bdate & "', '" & rodate & "'"
sql = sql & ", '" & hirereason & "', '" & roreason & "')"
sql = sql & " END COMMIT TRAN"
Cn.Execute (sql)
End If
I have some values and I'm formatting the date values which come is as string to date. If I run this as is it puts a default value for "" into the DB as 1900-1-1. I want the NULL values to actually stay in the DB and not be over-written. Furthermore I want them to update a cell with NULL if say it didn't use to be but now is.
I tried wrapping my value rodate in an IF statement and tried validating it against NULL, NOTHING, and EMPTY to say if it is one of these UPDATE DB with "NULL" but it doesn't do it. Date still comes out 1900-1-1. Any ideas?
Dim roDate
'...
'...
rodate = Trim(cell.Offset(0, 8).Value)
If len(rodate)=0 Then
rodate = null
else
rodate = "'" & Format(rodate, "yyyy-mm-dd") & "'"
end if
'....
'....
'note no single quote here around rodate
sql = sql & ", BillableDate='" & bdate & "', RollOffDate=" & rodate
'...
'...
I'm confused, not sure if I get this question right.
The only thing I understood from it is that you are struggling with saving a date as NULL in the database.
NULL and an empty string are not the same.
Try and see if this works:
dim vNull as variant
vNull = Null
if sDate = "" then
//Save vNull instead of Date
end if
I don't believe that you can capture NULL in a string datatype.
Edit
Perhaps stupid that I didn't think of this before, but instead of an empty string, can't you just put the string "NULL" in the query string?

Visual Studio Database custom criteria search wont work

I have created a database in Visual Studio and I am coding with VB.net I have created textboxes and checkboxes to match the fields that each will search when the search button is pressed .
whenever i perform a search using the text boxes and checkbox i get an error.
Item Name , Room , Broken, In Use, floor, are the fields searched by the tehe text in NameSearch, RoomSearch, BrokenSearchare, InUseSearch ,FloorSearchrespectivly ....etc
this is thee code for the search button
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
RecordDataGridView.Refresh()
Me.RecordBindingSource.Filter = "[Item Name]= '" & NameSearch.Text & "' And [Room]= '" & RoomSearch.Text & "' And [Make]= '" & MakeSearch.Text & _
"' And [Broken]= '" & BrokenSearch.CheckState & "' And [Replaced]= '" & ReplacedSearch.CheckState & "'And [ID#]= '" & IdentificationNumberSearch.Text & _
"' And [Floor]= '" & FloorSearch.Text & "' And [In Use]= '" & InUseSearch.CheckState & "'"
Me.RecordTableAdapter.Fill(Me.MLGDatabaseDataSet.Record)
RecordDataGridView.Refresh()
End Sub
the error
for example I enter a text into item nameSearch and floorSearch and press search ,no result will be turned up as the other text boxes have no text in them.
Without addressing other issues, such as using a parameterized query to prevent SQL injections or using StringBuilder to more efficiently perform concatenation, I believe your issue may be a missing space in this snippet:
ReplacedSearch.CheckState & "'And [ID#]= '"
if you change this to
ReplacedSearch.CheckState & "' And [ID#]= '"
it may resolve the immediate error. However, you almost certainly have additional logic errors introduced by the OR statement in the middle (you probably want to surround the two clauses that are ORed with parentheses).
I spotted the same thing as #competent_tech. I would set it up this way to make it easier to debug.
Dim strFilter As String = _
"[Item Name]= '" & NameSearch.Text & _
"' And [Room]= '" & RoomSearch.Text & _
"' And [Make]= '" & MakeSearch.Text & _
"' And [Broken]= '" & BrokenSearch.CheckState & _
"' Or [Replaced]= '" & ReplacedSearch.CheckState & _
"' And [ID#]= '" & IdentificationNumberSearch.Text & _
"' And [Floor]= '" & FloorSearch.Text & _
"' And [In Use]= '" & InUseSearch.CheckState & "'"
Debug.Print(strFilter)
RecordBindingSource.Filter = strFilter
Edit: you want to filter only when there are conditions given
'filter string
Dim strFilter As String = ""
'for check boxes you probably want to filter only if checked
If BrokenSearch.CheckState = CheckState.Checked Then strFilter += "And [Broken]= " & BrokenSearch.CheckState & " "
If ReplacedSearch.CheckState = CheckState.Checked Then strFilter += "And [Replaced]= " & ReplacedSearch.CheckState & " "
If InUseSearch.CheckState = CheckState.Checked Then strFilter += "And [In Use]= " & InUseSearch.CheckState & " "
'for text boxes you want to filter only if has text
If IdentificationNumberSearch.Text.Length > 0 Then strFilter += "And [ID#]= '" & IdentificationNumberSearch.Text & "' "
If FloorSearch.Text.Length > 0 Then strFilter += "And [Floor]= " & FloorSearch.Text & " "
If RoomSearch.Text.Length > 0 Then strFilter += "And [Room]= " & RoomSearch.Text & " "
If MakeSearch.Text.Length > 0 Then strFilter += "And [Make]= '" & MakeSearch.Text & "' "
If NameSearch.Text.Length > 0 Then strFilter += "And [Item Name]= '" & NameSearch.Text & "' "
'check to make sure there is at least one condition
If strFilter.Length > 0 Then
'remove the first "And"
strFilter = strFilter.Remove(0, 4)
'output
Debug.Print(strFilter)
'set to filter
RecordBindingSource.Filter = strFilter
End If
Edit: Your error "Cannot perform '=' operation on System.Boolean and System.String" I think the problem is that the filter value has to match the field type.
For strings do this: [Make] = 'stringValue' using single quotes;
For integers do this: [Floor] = 24 without single quotes;
For bit do this: [Broken] = 1 without single quotes;
It looks like Broken, Replaced and In Use are Bit type in the database. And I'm guessing that Floor and Room are Integer.

Resources