hie all,
i want to insert the data into the table only if the table is empty, so for that i need to check the condition to check whether data already exists in the table, if present then i want to empty the table before inserting the the fresh value.
i know how to insert and delete the data only prob is to check the condition. so please can any help me out in this.
TO INSERT
Dim comUserSelect As OleDbCommand
myDateTime(i) = DateTime.Parse(arr_dateTime(i))
' Console.WriteLine(r("P1"))
Dim strSELEsCTa As Integer = r("P1")
If ins < 10 Then
ins = ins + 1
Dim strSELECTa As String = "insert into tblvalues (DataTime ,P1) values ('" & DateTime.Parse(arr_dateTime(i)) & "','" & strSELEsCTa & "')"
Dim dadte_s As New OleDbDataAdapter(strSELECTa, conn)
comUserSelect = New OleDbCommand(strSELECTa, conn)
comUserSelect.ExecuteNonQuery()
End If
*TO DELETE *
Dim strDelete As String = "delete * from tblvalues "
now i don know how to check the condition
"SELECT COUNT(*) FROM your_table_name"
If the table is empty, this should return 0.
Alternatively, you could try to select a row from the table and based on the response act upon it.
"SELECT * FROM your_table_name LIMIT 0, 1"
Related
I am creating a form in an Access database that allows a user to import an Excel workbook into the database, then inserts a column with that day's date as a way to log when the record was imported, with the idea that I can later compare this to a master database and update accordingly.
My code is below:
Private Sub btnImport_Click()
'create a new file system object that will check for conditions and import the file as a new table if a valid name is chosen
Dim FSO As New FileSystemObject
Dim strSQL As String
'Dim curDatabase As Object
Dim tableTest As Object
Dim fieldNew As Object
Dim todayDate As Date
Dim tempTable As String
tempTable = "TempTable" & CStr(Date)
'MsgBox TempTable
'If no file name in box
If Nz(Me.txtFileName, "") = "" Then
MsgBox "Please choose a file."
Exit Sub
End If
'If a file name is in box and the file can be located
If FSO.FileExists(Me.txtFileName) Then
fileImport.ImportExcel Me.txtFileName, tempTable
'once it imports the table, it then adds today's date (the upload date)
todayDate = Date
strSQL = "INSERT INTO tempTable (Upload_Date) Values (#" & Date & "#);"
DoCmd.RunSQL strSQL
'DoCmd.RunSQL ("DROP Table TempTable")
Else
'Error message if file can't be found
MsgBox "File not found."
End If
End Sub
Unfortunately, right now I am getting two problems.
The first is
run-time error 3127: The INSERT INTO statement contains an unknown
field name.
I thought I wanted to insert a new field, so I'm a little perplexed by this error.
I'm also getting another error; the compiler doesn't seem to like when I use tempTable for the table name. I'm trying to use a reference to the table name, rather than the actual name of the table itself, because this will end up being a daily upload, so the name of the table that is having this column inserted into it will change every day.
I appreciate any guidance that you can give; I'm fairly new to VBA.
UPDATE: I ended up solving this issue by A. using an UPDATE statement and using CurrentDb.Execute to add the date. I found that this worked for me:
strSQL = "ALTER TABLE TempTable ADD COLUMN Upload_Date DATE;"
strSQL2 = "UPDATE TempTable SET Upload_Date = '" & Date & "'"
DoCmd.RunSQL strSQL
CurrentDb.Execute strSQL2
INSERT INTO doesn't add columns, it just adds rows (with data in existing columns). Look into ALTER TABLE ( https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/alter-table-statement-microsoft-access-sql )
I'm not sure if it's related, but the table name you use in strSQL is "tempTable", yet the table name you pass to fileImport.ImportExcel is "TempTable" (i.e. the capitalization of the first letter is inconsistent).
If the variable "tempTable" is meant to hold the name of the table (so it can be used for different table names) then it should be outside of the SQL strings:
strSQL= "ALTER TABLE " & tempTable " & " ADD COLUMN Upload_Date DATE;"
strSQL2 = "UPDATE " & tempTable & " SET Upload_Date = '" & Date & "';"
Otherwise you are amending and updating a table called "TempTable" rather than inserting the calculated table name from the variable into the SQL string.
Also note that there should be a semi-colon at the end of strSQL2 as well.
For i As Integer = 0 To dgclassinfo.Rows.Count - 1
LRN = dgclassinfo.Rows(i).Cells(2).Value.ToString
Lname = dgclassinfo.Rows(i).Cells(3).Value.ToString
Fname = dgclassinfo.Rows(i).Cells(4).Value.ToString
Mname = dgclassinfo.Rows(i).Cells(5).Value.ToString
comm.CommandText = "insert into g7(LRN,Lname,Fname,Mname ) values('" & LRN & "','" & Lname & "','" & Fname & "','" & Mname & "')"
comm.ExecuteNonQuery()
Next
I used to code above to import my data. Using dgv. My data is databound. for additional info. When I import the file it reads the value of the excel and displays in the dgv in which i insert the data using the for loop above. I think I need to use mydr.hasrows but I have no idea on how to do this using for loop. How can I check for duplicate records every row? LRN is my pk.
Any help will be appreciated.
To check if record exists, u can actually check the database's specific column to see if the column has any rows containing the same record u are trying to insert..TO do this,first u need to check the database for duplicates and then insert new data if no duplicates exist.A full example might look like this :
Dim cmd as new SqlCommand("Select * from TABLENAME([column names-remove brackets if required])values(#value1)",con)
cmd.parametres.AddWithValue("#value1",Firstname.Text)
Dim dr as new SqlDataReader=cmd.Executereader
If dr.hasRows Then 'This checks if any duplicates exist
Msgbox("Duplicates Found")
Else
Dim cmd as new SqlCommand("Inserting data query here",con)
cmd.parametres.Add("#value1",SqlDbtype.Varchar).value=Firstame.Text
cmd.ExecuteNonQuery
Here i've assumed u r using Sql Server, make necessary changes to the code
I cannot seem to figure out how to get an output of a SQL query as a variable in VB. I need something like what's below so that I can use that variable in another SQL query. SQL doesn't allow the use of variables as column headers when running queries, so I thought I could use VB to insert the actual output of one SQL task as the dynamic variable in a loop of update queries. Let me (hopefully) explain.
I have the following query:
DECLARE #id int = (SELECT max(id) FROM [views]), #ViewType nvarchar(3);
WHILE #id IS NOT NULL
BEGIN
SELECT #ViewType = (SELECT [View] FROM [views] WHERE id = #id);
UPDATE a
SET a.[#ViewType] = '1'
FROM [summary] a
INNER JOIN [TeamImage] b
ON a.[Part_Number] = b.[PartNum]
WHERE b.[View] = #ViewType;
SELECT #id = max(id) FROM [views] WHERE id < #id;
END;
The SET a.[#ViewType] = '1' obviously will not work in SQL. But if I could have the (SELECT [View] FROM [views] WHERE id = #id) equal to a variable, then I could write the SQL query in VB and execute it and the variable would become part of the string and therefore execute correctly.
I'm newer to VB, but here's what I have so far:
Dim cn As SqlConnection = New SqlConnection("Data Source=Server1;" & _
"Initial Catalog=DB1;" & _
"Integrated Security=SSPI")
cn.Open()
Dim cmd As New sqlCommand("SELECT max(id) FROM orientation_view_experiment;", cn)
vID = cmd.ExecuteNonQuery()
Do While vID > 0
Dim cmd2 As New sqlCommand("SELECT [View] FROM [views] WHERE id ='" + vID + "'"
vViewType = cmd2.ExecuteNonQuery()
Dim cmd3 As New sqlCommand("UPDATE a
SET a.'" + vViewType + "' = '1' & _
FROM [summary] a & _
INNER JOIN [TeamImage] b & _
ON a.[Part_Number] = b.[PartNum] & _
WHERE b.[View] = '" + vViewType + "';"
cmd3.ExecuteNonQuery()
vID = vID - 1
Loop
cn.Close()
I hope some of that made sense, but I'm kind of lost at this point. I feel like I know what I need the SQL to do, but can't quite figure out how to make the computer/programs submit to my will and just do what I need it to do.
Thank you for any help/direction you can give.
Your code is wrong because you insist in using ExecuteNonQuery for SELECT statements. ExecuteNonQuery doesn't return the rows selected but just a count of the rows affected by an INSERT/DELETE/UPDATE query (I think that for SELECT it returns always zero)
What you need is ExecuteScalar to get the MAX value and the VIEW value because ExecuteScalar is the best choice when you expect to get just the first field of the first row from your SQL statement
Dim cmd As New sqlCommand("SELECT max(id) FROM orientation_view_experiment;", cn)
vID = Convert.ToInt32(cmd.ExecuteScalar())
Do While vID > 0
Dim cmd2 As New sqlCommand("SELECT [View] FROM [views] WHERE id =" + vID.ToString()
Dim result = cmd2.ExecuteScalar()
if Not string.IsNullOrEmpty(result)) Then
vViewType = result.ToString()
Dim cmd3 As New sqlCommand("UPDATE a SET a.[" + vViewType + "] = '1' " & _
"FROM [summary] a " & _
"INNER JOIN [TeamImage] b " & _
"ON a.[Part_Number] = b.[PartNum] " & _
"WHERE b.[View] = #vType"
cmd3.Parameters.AddWithValue("#vType", vViewType)
cmd3.ExecuteNonQuery()
End If
Loop
The last part of your code is not really clear to me, but you could use a couple of square brackets around the column name in table summary and a parameter for the View field in table TeamImage.
As a last advice, be sure that the column View in table TeamImage is not directly modifiable by your end user because a string concatenation like this could lead to a Sql Injection attacks
Do a little research into what the different methods of a command are. When you call ExecuteNonQuery, this return the number of records effected. I think you want ExecuteScalar as your cmd and cmd2 methods, so you can get a value from the database.
Have you tried replacing '" + vViewType + "' with [" + vViewType + "] ... in other words use square brackets to delimit the column name instead of single quotes which are for delimiting string literals?
Also, I would encourage stopping in the debugger, examining the command that you generated into cmd3 and try executing it directly. It might help you identify other similar problems such as the fact that vViewType is giving you a count of records instead of an actual value from the [View] column.
I have records from server that I want to copy, so I used datareader to select all, during selection the insert also process.
This is the pseudo code:
while datareader.read
For f As Integer = 0 To datareader.FieldCount - 1
Values = Values & datareader.GetValue(f)
Next
Dim ss as string ="Insert into xtable(a,b,c,d,e,f) select " & values & " where not Exist (select * from xtable)" ''//is this right?
Dim sc as new sqliteCommand(ss,mycon)
sc.ExecuteNonQuery
End While
sc.dispose
What is the exact sql statement to insert only if record doesn't exist in my current table?
I used some of this code, but a filter was defined: like x
What if I just want to insert records that doesn't exist in the table I want.
Dim ss As String = "insert into xtable(x,y,z) select $x, $y,$z
where not exists (select 1 from xtable where x=$x)"
Try this:
if not exists(select 1 from xtable)
begin
insert into xtable(x,y,z) select $x, $y,$z from xtable
end
I don't think the above will work, but this link should give you the answer you're looking for.
i am inserting values into a table
if the record exists already replace it, and if it does not exist then add a new one.
so far i have this code:
INSERT INTO table_name
VALUES (value1, value2, value3,...) where pk="some_id";
but i need something like this
if not pk="some_id" exists then INSERT INTO table_name
VALUES (value1, value2, value3,...) where pk="some_id"; else update table_name where pk="some_id"
what would be the correct SQL syntax for this?
please note that i am using sql access and that i guess it can be a combination of vba and sql
First update rows which match between your import table and master table.
UPDATE table_name AS m
INNER JOIN tblImport AS i
ON m.pk = i.pk
SET
m.field2 = i.field2,
m.field3 = i.field3,
m.field4 = i.field4;
Then add any imported records which don't exist in the master table.
INSERT INTO table_name (
pk,
field2,
field3,
field4)
SELECT
i.pk,
i.field2,
i.field3,
i.field4
FROM
tblImport AS i
LEFT JOIN table_name AS m
ON i.pk = m.pk
WHERE
(((m.pk) Is Null));
This could be done easily with recordsets. The code would then look like that (for an ADODB recordset):
myRecordset.find ....
if myRecordset.EOF then
myRecordset.addNew
endif
....
myRecordset.fields(...) = ...
....
myRecordset.update
I have posted about my approach to this problem many, many times in many different forums, but I'll just recapitulate the basic structure of the approach I use. There is no way to do it in one step, though.
update the existing records from the external data source.
insert records that don't already exist.
This assumes a common primary key that can be used to link the existing table with the external data source.
Task #2 is pretty trivial, just an outer join for the records that don't already exist.
One can use brute force for #1, writing an UPDATE statement with a SET for each field other than the primary key, but I consider that to be messy and unnecessary. Also, since I have a lot of replicated applications, I can't do that, as it would result in false conflicts (when a field is updated to the same value as it started with).
So, for that purpose, I use DAO and write an on-the-fly SQL statement to update COLUMN-BY-COLUMN. The basic structure is something like this:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim fld As DAO.Field
Dim strField As String
Dim strSet As String
Dim strWhere As String
Dim strSQL As String
Set db = CurrentDB
Set rs = db.OpenRecordset("DestinationTable")
For Each fld in rs.Fields
strField = fld.Name
If strField <> "PKField" Then
strSet = "DestinationTable." & strField & " = ExternalTable." & strField
strWhere = "Nz(DestinationTable." & strField & ",'') = Nz(ExternalTable." & strField & ", '')"
strSQL = "UPDATE DestinationTable "
strSQL = strSQL & " SET " & strSet
strSQL = strSQL & " WHERE " & strWhere
db.Execute strSQL, dbFailOnError
Debug.Print strField & ": " & db.RecordsAffected
End If
Next fld
Now, the complicated part is handling numeric vs. date vs. string fields, so you have to have some logic to write the WHERE clauses to use proper quotes and other delimiters according to the field type. Rather than test the field type, I generally just use a CASE SELECT like this, making string fields the default:
Dim strValueIfNull As String
Select Case strField
Case "DateField1", "DateField2", "NumericField2", "NumericField2", "NumericField3"
strValueIfNull = "0"
Case Else
strValueIfNull = "''"
strWhere = "Nz(DestinationTable." & strField & ", '') = Nz(ExternalTable." & strField & ", '')"
End Select
strWhere = "Nz(DestinationTable." & strField & ", " & strValueIfNull & ") = Nz(ExternalTable." & strField & ", " & strValueIfNull & ")"
I could have the details there wrong, but you get the idea, I think.
This means you'll run only as many SQL updates as there are updatable fields, and that you'll only update records that need updating. If you're also stamping your records with a "last updated" date, you'd do that in the UPDATE SQL and you'd only want to do that on the records that really had different values.