Line break in an INSERT INTO statement - sql

I have searched all the boards and can not find were anyone has asked how to do a line break in code for INSERT INTO statement. I have tried many variations, I can seem to get any of them to work. He is an example of my code and what I am trying. I know it is just a misplaced comma, quote or ampersand.
StrSQL = "INSERT INTO Tbl_Data_Shop & _
(ClaimNumber, ExposureNumber, ClaimSuffix, & _
Shop_Name, Shop_StreetAddress, Shop_City, & _
Shop_State, Shop_Zip, Shop_Phone) & _
"Values
('" & Forms!Frm_Data_Main!TBClaimNumber & "' & _
"'" & Forms!Frm_Data_Main!TBExposureNumber & "' & _
"'" & Forms!Frm_Data_Main!TBClaimSuffix & "'," & _
"'" & TBSShop_Name & "'," & _
"'" & TBSShop_StreetAddress & "'," & _
"'" & TBSShop_City & "'," & _
"'" & TBSShop_State & "'," & _
"'" & TBSShop_Zip & "'," & _
"'" & TBSShop_Phone & "'");"

Once again, a classic example to use the industry best practice of parameterization which you can do in MS Access with QueryDefs.Parameters. Beyond protecting against sql injection, you avoid any need to worry about quotes or ampersands with string interpolation and arguably build a more readable and maintainable code block.
Regardless of language (here being VBA), the process involves setting up a prepared SQL statement with placeholders. Then in a different step you bind data values to placeholders for execution.
SQL
Save below as a saved MS Access query (Ribbon > Create > Queries > SQL View). This SQL query uses the PARAMETERS clause (valid in Access SQL dialect) to define placeholders and their types and then uses the placeholders. You can break all the lines you want!
PARAMETERS TBClaimNumberParam TEXT(255), TBExposureNumberParam TEXT(255),
TBClaimSuffixParam TEXT(255), TBSShop_NameParam TEXT(255),
TBSShop_StreetAddressParam TEXT(255), TBSShop_CityParam TEXT(255),
TBSShop_StateParam TEXT(255), TBSShop_ZipParam TEXT(255),
TBSShop_PhoneParam TEXT(255);
INSERT INTO Tbl_Data_Shop (ClaimNumber, ExposureNumber, ClaimSuffix,
Shop_Name, Shop_StreetAddress, Shop_City,
Shop_State, Shop_Zip, Shop_Phone)
VALUES (TBClaimNumberParam, TBExposureNumberParam, TBClaimSuffixParam,
TBSShop_NameParam, TBSShop_StreetAddressParam, TBSShop_CityParam,
TBSShop_StateParam, TBSShop_ZipParam, TBSShop_PhoneParam)
VBA
In this step, you reference the above saved query, mySavedQuery, into a QueryDef object which then has VBA values binded to the query's named parameters (defined in above SQL).
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
' BIND VALUES TO PARAMETERS
qdef!TBClaimNumberParam = Forms!Frm_Data_Main!TBClaimNumber
qdef!TBExposureNumberParam = Forms!Frm_Data_Main!TBExposureNumber
qdef!TBClaimSuffixParam = Forms!Frm_Data_Main!TBClaimSuffix
qdef!TBSShop_NameParam = TBSShop_Name
qdef!TBSShop_StreetAddressParam = TBSShop_StreetAddress
qdef!TBSShop_CityParam = TBSShop_City
qdef!TBSShop_StateParam = TBSShop_State
qdef!TBSShop_ZipParam = TBSShop_Zip
qdef!TBSShop_PhoneParam = TBSShop_Phone
' EXECUTE ACTION
qdef.Execute dbFailOnError
Set qdef = Nothing

Make each line a string on its own - and correct the commas and parenthesis:
StrSQL = "INSERT INTO Tbl_Data_Shop " & _
"(ClaimNumber, ExposureNumber, ClaimSuffix, " & _
"Shop_Name, Shop_StreetAddress, Shop_City, " & _
"Shop_State, Shop_Zip, Shop_Phone) " & _
"Values (" & _
"'" & Forms!Frm_Data_Main!TBClaimNumber & "'," & _
"'" & Forms!Frm_Data_Main!TBExposureNumber & "'," & _
"'" & Forms!Frm_Data_Main!TBClaimSuffix & "'," & _
"'" & TBSShop_Name & "'," & _
"'" & TBSShop_StreetAddress & "'," & _
"'" & TBSShop_City & "'," & _
"'" & TBSShop_State & "'," & _
"'" & TBSShop_Zip & "'," & _
"'" & TBSShop_Phone & "');"

There are missing/misplaced quotation marks and &s . However I would use a prepared statement, for a number of reasons, namely safety and managability .
StrSQL = "INSERT INTO Tbl_Data_Shop & _
(ClaimNumber, ExposureNumber, ClaimSuffix, & _
Shop_Name, Shop_StreetAddress, Shop_City, & _
Shop_State, Shop_Zip, Shop_Phone) & _
Values ('" & Forms!Frm_Data_Main!TBClaimNumber & "', & _
'" & Forms!Frm_Data_Main!TBExposureNumber & "', & _
'" & Forms!Frm_Data_Main!TBClaimSuffix & "', & _
'" & TBSShop_Name & "', & _
'" & TBSShop_StreetAddress & "', & _
'" & TBSShop_City & "', & _
'" & TBSShop_State & "', & _
'" & TBSShop_Zip & "', & _
'" & TBSShop_Phone & "');"
Try and let us know.

Related

VBA Insert static value into SQL table

I've used VBA to insert into an SQL table before but its always been using values in cells. I have three columns in my table where I need to add just a static value (so no cell reference).
The code I have so far is:
stSQL = "INSERT INTO Client_Notes " & _
"(ID, Category, RefID, Name, Notes, Date_Loaded, Latest) " & _
" VALUES (" & _
"'" & 1 & "', " & _
"'" & 1 & "', " & _
"'" & Sheets("Missing").ActiveCell.Offset(0, -10).Value & "', " & _
"'" & Sheets("Missing").ActiveCell.Offset(0, -9).Value & "', " & _
"'" & Sheets("Details").ActiveCell.Value & "', " & _
"'" & Date & "', " & "'" & _
"'" & 1 & "'" & _
")"
The error I keep getting is when trying to insert 1 as a value. I'm sure its straight forward but feel like I had tried every quote and comma combination going.
Thanks in advance
So the new code now looks like so, where I am getting Subscript Out Of Range:
stSQL = "INSERT INTO Client_Notes " & _
"(ID, Category, RefID, Name, Notes, Date_Loaded, Latest) " & _
" VALUES (" & _
"1, " & _
"1, " & _
"'" & Sheets("Missing").Range("L" & i).Offset(0, -10).Value & "', " & _
"'" & Sheets("Missing").Range("L" & i).Offset(0, -9).Value & "', " & _
"'" & Sheets("Details").Range("L" & i).Value & "', " & _
"'" & Date & "', " & _
"1)"

how can i insert into? my error is no value given for one more required parameters

my error is no value given for one more required parameters.
my fields new,rev1,rev2,rev3,rev4,rev5 i need to convert to date.
cmd.CommandText = "INSERT INTO [sheet] ([empno],[empname],[projectname],[sheetno],[title],[new],[rev1],[rev2],[rev3],[rev4],[rev5) VALUES (empno ='" _
& txtempno.Text & "',empname ='" & txtemp1.Text _
& "',projectname = '" & Txtpro.Text & "',sheetno = '" _
& txtdrawing.Text & "',title = '" & txtdesc.Text _
& "', _
new = CDate('" & date1txt.Text & "'), _
rev1 = CDate('" & date2txt.Text & "'), _
rev2 = CDate('" & date3txt.Text & "'), _
rev3 = CDate('" & date4txt.Text & "'),_
rev4 = CDate('" & date5txt.Text & "'), _
rev5 = CDate('" & date6txt.Text & "'))"
First of all look at this line
[rev4],[rev5)
] is missing in [rev5].
Second thing is that you don't need to assign parameter name here
",empname ='" & txtemp1.Text & "'"
it is better to create parameterized query instead of concatinating string. hackers can easily inject the sql injection in your query.
Values(#empno, #empname,...)
or
Values(?, ?,...)

VBA SQL Join Query

I am having troubles with a VBA SQL JOIN. I Keep Getting A "Join Expression Not Supported" Error. The Following Code Works In The Query Design View but seems to throw an error when in vba.
Dim Rs As DAO.RecordSet
Set Rs = CurrentDb.OpenRecordset( _
"SELECT Schools.ID, Schools.[School Name],Schools.Address, Schools.Postcode, Schools.[Principal name], " & _
"Schools.[E-Mail], Schools.Phone, Schools.Region, Schools.JTHE, Schools.[Social Status], Events.Program " & _
"FROM Schools INNER JOIN Events ON Schools.ID = Events.School WHERE ((Schools.Region = '" & RegionOne & _
"' Or Schools.Region = '" & RegionTwo "' Or Schools.Region = '" & RegionThree "' Or Schools.Region = '" & _
RegionFour "') AND (Schools.JTHE = " & JTHE1 & " Or Schools.JTHE = " & JTHE2 ") AND (Schools.[Social Status] = '" & _
StatusBox.Value "') AND (Events.Program = '" & ProgramBox.Value & "'));")
This Similar Query Works
Set Rs = CurrentDb.OpenRecordset("SELECT * FROM Schools WHERE " & _
"(((Schools.Region)='" & RegionOne & _
"' Or (Schools.Region)='" & RegionTwo & _
"' Or (Schools.Region)='" & RegionThree & _
"' Or (Schools.Region)='" & RegionFour & _
"') AND ((Schools.[Social Status])='" & StatusBox.Value & _
"') AND ((Schools.JTHE)=" & JTHE1 & " Or (Schools.JTHE)=" & JTHE2 & "));")
Any help would be greatly appreciated.
I'm not entirely sure why is that. It is hard to spot error when your doing it on VBA, unlike if your in an actual SQL Management studio where you can spot the lines that errors out. Nonetheless, you may try this:
Set Rs = CurrentDb.OpenRecordset( _
"SELECT Schools.ID, Schools.[School Name], Schools.Address, " & _
"Schools.Postcode, Schools.[Principal name], Schools.[E-Mail], " & _
"Schools.Phone, Schools.Region, Schools.JTHE, Schools.[Social Status], " & _
"Events.Program " & _
"FROM Schools " & _
"INNER JOIN Events " & _
"ON Schools.ID = Events.School " & _
"WHERE Schools.Region IN (" & _
"'" & RegionOne & "'," & _
"'" & RegionTwo & "'," & _
"'" & RegionThree & "'," & _
"'" & RegionFour & "') " & _
"AND Schools.JTHE IN (" & JTHE1 & ", " & JTHE2 & ") " & _
"AND Schools.[Social Status]='" & StatusBox.Value & "' " & _
"AND Events.Program='" & ProgramBox.Value & "';")
I formatted it as such to give you the story of the query (and that is how I will write it in SQL). Not really a direct to the point answer to your question but I just simplified your OR statements and instead uses IN. You might get a:
Too many continuous line error
So adjust the concatenation of strings. I have not tested this of course (although it compiles) but my goal is to give you idea on a possible way to do it. HTH.

I'm trying to UPDATE some fields in my table in Access VBA

I need some help with this, sorry, I am new in VBA and I am trying to run a update query which should obtain a value from a variable and update an already existing table. This is done using VBA. On executing no error message is shown but the table isn't updated with the new value. The code is as follows:
Query = "UPDATE Results " & _
"SET fk_Report='" & Report & "'" & _
",fk_Name='" & Namevar & "'" & _
",fk_Age='" & Agevar & "'" & _
",fk_Sex='" & Sexvar & "'" & _
"WHERE [Count]='" & Countvar & "'" & _
",[Positives]='" & Posvar & "'" & _
",[Negatives]='" & Negvar & "'" & _
",[Unknow]='" & Unkvar & "';"
CurrentDb.Execute (Query)
If somebody can help...
You don't need the commas in the where clause
Query = "UPDATE Results " & _
"SET fk_Report='" & Report & "'" & _
",fk_Name='" & Namevar & "'" & _
",fk_Age='" & Agevar & "'" & _
",fk_Sex='" & Sexvar & "'" & _
"WHERE [Count]='" & Countvar & "' " & _
"AND [Positives]='" & Posvar & "' " & _
"AND [Negatives]='" & Negvar & "' " & _
"AND [Unknow]='" & Unkvar & "';"
CurrentDb.Execute (Query)
use AND instead of , (comma) after WHERE clause

Microsoft Access 2010 VB InsertInto syntax error

I am totally new to Microsoft Access and VB, what i am trying to do is i have a form with unbounded textboxes which i would like upon clicking a button save the text in each textbox in its unique field.
I managed to write this piece of code with some help from online resources but it keeps giving me syntax error, if someone could point me into the correct way.
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
Since are IT-DEC-MAKER-FNAME and IT-DEC-MAKER-LNAME are invalid identifiers in SQL, you must enclose them in brackets ([ ])
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
UPDATE:
I have two nice helper functions for this kind of things.
This one replaces placeholders in a string with values
Function Build(ByVal s As String, ParamArray args()) As String
' Build("LastName = {0}, FirstName = {1}","Dow","John") --> "LastName = Dow, FirstName = John".
' "\n" will be converted to vbCrLf.
Dim i As Long
s = Replace(s, "\n", vbCrLf)
For i = 0 To UBound(args)
s = Replace(s, "{" & i & "}", Nz(args(i)))
Next i
Build = s
End Function
This one converts a variant value supposed to contain a text in to a SQL value
Public Function SqlStr(ByVal v As Variant) As String
' NULL Returns: NULL
' "" Returns: NULL
' "abc" Returns: 'abc'
' "x'y" Returns: 'x''y'
Dim s As String
s = Nz(v)
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function
You can then use them like this making your code safer and easier to understand.
Dim template As String, sql As String
template = "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8},{9});"
sql = Build(template, _
SqlStr(Me.qfirstname), SqlStr(Me.qlastname), _
SqlStr(Me.qjob), SqlStr(Me.qphone), _
SqlStr(Me.qmobile), SqlStr(Me.qemail), _
SqlStr(Me.qfax), SqlStr(Me.qitfirstname), _
SqlStr(Me.qitlastname))
CurrentDb.Execute sql
I suggest you lay out your code like so:
sSQL = "INSERT INTO UserInformation(" _
& "FirstName, LastName, Company, JobTtile, " _
& "PhoneNumber, Mobile, Email, Fax, " _
& "IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " _
& "VALUES('" _
& Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & Me.qjob _
& "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & Me.qfax _
& "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
CurrentDB.Execute sSQL, dbFailOnError
It makes it much easier to see mistakes and the sSQL string can be printed to the immediate window for debugging. You will see you have JobTtile.
It is usually better to use an instance of CurrentDB:
Dim db As DAO.Database
Set db = CurrentDB
I wonder why you do not just bind a recordset?