I have the following VB statement for inserting text data to a SQL 2008 DB. How can I check if sValueList already exists in sFieldNameList column while doing the insert?
sInsertStatement = "INSERT " & sTableName
& "(" & sFieldNameList & ") VALUES("
& Mid(sValueList , 3) & ")"
I would do it as follows:
"IF NOT EXISTS (SELECT * FROM " & sTableName * "
WHERE " & sFieldNameList & " = " & sValueList & ")
BEGIN
"INSERT " & sTableName
& "(" & sFieldNameList & ") VALUES("
& Mid(sValueList , 3) & ")"
END
(this needs to be adapted to a VBScript syntax though!)
You need to do either UPDATE or INSERT? What you need is an UPSERT command. Basically you need a WHERE clause like:
where not exists (select 1 from mytable where col2='myId').
Read here how postgres do it.
sql2008 does not have same functionality but check this blog (end of page) where they do:
USE [MyDatabase]
GO
merge into mytable as Target
using mytable2 as Source
on Target.id=Source.id
when matched then
update set Target.name=Source.name,
Target.Salary = Source.Salary
when not matched then
insert (id,name,salary) values (Source.id,Source.name,Source.Salary);
Related
I'm out of my league on this... Another developer before me did something similar to what I want to do by adding a value in a table while updating another table. However, he was running updates as well as inserting, and his primary key was text. Mine PK is integer. Here's his code (works great) that I am trying to reverse engineer and apply to my situation:
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT ReportPK FROM
ACIST_MobilePipelineReportReviewed WHERE ReportPK = '" & ReportPk & "') " &
_
" UPDATE ACIST_MobilePipelineReportReviewed set Status = 'Approved'
WHERE ReportPK = '" & ReportPk & "'" & _
" ELSE " & _
" INSERT INTO ACIST_MobilePipelineReportReviewed ([ReportPK],
[PipelineUID],[ReportDate],[ReportInspector],[Status]) VALUES (" & _
"'" & ReportPk & "','" & Me!PipelineUID & "','" & Me!ReportDate & "','"
& Me!ReportInspector & "','Approved')"
End Sub
Here's what I'm doing: I have a combo box on a form called FacilityEntryF. That form is tied to my FacilityT table. I am selecting "CampaignID" from the CampaignT table and adding it to the FacilityT using that combo box in the aforementioned form. No biggie there... Works great.
The FacilityT has many columns of which I have [FacilityID] which is the primary key and is an autogenerated integer. It also has a column for [CampaignID] which is a foreign key from the CampaignT table.
After adding the CampaignID and starting a new FacilityID in FacilityT, I also want to create a new record in my CampaignFacilityParticipationT table. That table consists of only three columns: CampaignFacilityParticipationID, CampaignID, ParticipantFacilityID. I want to take the new [FacilityID] and the [CampaignID] I added to that table and insert them into the CampaignFacilityParticipationT table (FacilityID goes into the ParticipantFacilityID column). Here's the code below that didn't work (which I'm not surprised because I don't know what I'm doing):
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID =
" & FacilityID) " & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID]) VALUES (" & _
"" & CampaignFacilityParticipationID,'" & Me!CampaignID," & Me!ParticipantFacilityID, CampaignID)"
End Sub
Using MS Access 2013 with Microsoft SQL backend.
Thanks!!!
Concatenation is not correct. If apostrophes are needed to delimit parameters then make sure they are used consistently. Normally in Access, apostrophes would only be used for text fields, # for date/time and nothing for number. Maybe because backend is MS SQL apostrophes are needed for all field types? Why do you repeat CampaignID in VALUES clause?
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID = '" & Me!FacilityID & "')" & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID])" & _
" VALUES ('" & Me!CampaignFacilityParticipationID & "','" & Me!CampaignID & "','" & Me!ParticipantFacilityID & "')"
Is it possible for you to use a subform on FacilityEntryF on which you select the CampaignID? That will eliminate the need for this code.
In the below code, the value of skuSet.Fields(0), which is a text field in the database, is "000000002".
If skuSet.RecordCount = 0 Then
sql = "SELECT Stock_Code FROM Stock WHERE Stock_Code = '" & stkLine.StockCode & "'"
Set skuSet = dbStock.OpenRecordset(sql, dbOpenDynaset)
End If
sql = "SELECT * FROM PickedByPicco WHERE OrderID = " & stkLine.OrderId & " AND StockCode = '" & skuSet.Fields(0) & "'"
Set SOPSLineSet = dbSOPS.OpenRecordset(sql, dbOpenDynaset)
If SOPSLineSet.RecordCount = 0 Then
sql = "INSERT INTO PickedByPicco(OrderID, StockCode, Qty, ScannedBy, ProcessedBy, processed) VALUES(" & stkLine.OrderId & _
", " & skuSet.Fields(0) & ", " & stkLine.Quantity & ", '" & stkLine.UserId & "', '', False)"
dbSOPS.Execute (sql)
When I step through the code, the value in skuSet.Fields(0) is still the same, as expected.
When the query has been executed, I check the PickedByPicco table, and the StockCode field shows just a value of 2 instead, and it's removed all of the leading 0's.
Why would it be doing this and how can I stop it?
That's because your INSERT statement looks like this:
INSERT INTO PickedByPicco (...) VALUES (..., 000000002, ...)
when it should look like this:
INSERT INTO PickedByPicco (...) VALUES (..., '000000002', ...)
(Note the quotes around your value.)
Normally, I'd tell you to use parameterized SQL, because SQL creation by string concatenation is evil, but, unfortunately, DAO's Database.Execute does not support that. So, the next best thing is to properly escape strings. To do that:
put single quotes around your value and
escape any single quotes occurring in your value:
I.e. this line
", " & skuSet.Fields(0) & ", " & ...
becomes
", '" & Replace(skuSet.Fields(0), "'", "''") & "', " & ...
While you are at it, be sure to replace single quotes in your other strings as well! Currently, a UserId of O'Brien would break your SQL, and other values might do worse.
So all I'd like to do is add two queries into a table called tmpGroupSearch. I'm not sure how to do it wit out creating a record set and looping through every record and individually adding them in. I'm thinking there is a much easier way to do this I just can't find the proper structure.
Here are my queries:
"SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
"Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
You can follow an INSERT INTO clause with a list of values, like #Asad shows, or also a SELECT query. Do yourself a favor and always list the field names in your SQL or you are just creating time bombs for the future.
Dim strSelect1 As String
Dim strSelect2 As String
strSelect1 = "SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
strSelect2 = "Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
Dim strInsert1 As String
Dim strInsert2 As String
strInsert1 = "INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown) " & strSelect1
'the next version is valid SQL, but *dangerous* because field names are not enumerated
strInsert2 = "INSERT INTO tmpGroupSearch " & strSelect2
It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Test this parameter query in the Access query designer and adjust as needed so that it returns the row set you expect for the pSearchText parameter value you supply.
PARAMETERS pSearchText Text ( 255 );
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
FROM
tblGroupHeader AS gh
LEFT JOIN tblAlsoKnown AS ak
ON gh.GroupNum = ak.GroupNum
WHERE
gh.GroupName Like "'" & pSearchText & "*'"
OR gh.GroupNum Like "'" & pSearchText & "*'"
UNION ALL
SELECT al.GroupName, al.GroupNum, al.AlsoKnown
FROM tblActionLog AS al
WHERE al.AlsoKnown Like "'" & pSearchText & "*'"
Once you have it returning the correct data, convert it to an INSERT query by changing the beginning of the statement to this ...
PARAMETERS pSearchText Text ( 255 );
INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown)
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
... and the rest
Save that query as qryGroupSearchAppend. Then you can execute that query from your VBA code:
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("qryGroupSearchAppend")
qdf.Parameters("pSearchText").Value = Me.txtgroupSearch.Value
qdf.Execute dbFailOnError
I'm trying to fix it about hour but it's not work Please help me :(
CurrentDb.Execute "INSERT INTO match_day( home_team, away_team, date, time, home_score, away_score, stadium) " & _
" VALUES('" & Me.textHT & "','" & Me.textAT & "',#" & Me.textDATE & "#,#" & Me.textTime & "#," & Me.textHS & "," & Me.textAS & ",'" & Me.textSTD & ",')"
Are the fields for date and time considered reserved words and should be wrapped in brackets or ticks to qualify it as the column name...
..., [date], [time], ...
But I think it is most likely the trailing final comma before your final closing ) of the inserted values making it look like it wants another field to be inserted.
Me.textSTD & ",')"
change to
Me.textSTD & "')"
I ran into a similar error - thanks to this post I realised that I had used a reserved name "note" in a table ( instead of "notes").
StrSQL = "INSERT INTO option_notes ( OPTION_ID , USER_ID , [NOTE] ) VALUES ( " & currID & " , " & currUserID & " , '" & currNote & "' ) ; "
CurrentDb.Execute StrSQL
I ended up changing the field name - however, wrapping the field name with [ ] allowed the code to execute correctly.
So I am writing a string in VBA. It needs to use 2 different numeric variables from a form that the user clicked on. My code works great if I only use 1 variable, but I can't get the syntax correct for 2 variables. Here is what I originally wrote that works fine.
stringSQL = "select table1.field1, table2.field2 from table1 where table1.flag='flag' and
table1.weight = " & [Forms]![myform]![weight]
When I try to add age to the string (I want to use age and weight from myform) I write this which does not work -
stringSQL = "select table1.field1, table2.field2 from table1 where table1.flag='flag' and
table1.age= " & [Forms]![myform]![age] & " and " & table1.weight= " &
[Forms]![myform]![weight]
stringSQL = "select table1.field1, table2.field2 " & _
" from table1 where table1.flag='flag' " & _
" and table1.age= " & [Forms]![myform]![age] & _
" and table1.weight= " & [Forms]![myform]![weight]