insert if not exists in sqlite with vb.net - sql

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.

Related

Access 2010 - Determine existence of record in one of three remote mdb files for subsequent select

There are three mdb files in folders on a network drive that may hold the required record(s). How do I determine which db holds the record(s), ideally without data transfer/linking/etc.? Then a single SQL or DAO select can get the data from the correct db. Note: I'm trying to use Access as a front end to SQL using existing Access data spread all around the network drives.
My current solution of configuring 3 DAO objects and checking for no results, in succession until found, seems to load the remote tables to the local recordset and takes too long.
Is there a way to use IF EXISTS in this scenario?
This code throws "Invalid SQL statement; expected DELETE,INSERT,PROCEDURE,SELECT,OR UPDATE" error but is generally what I'd like to do :
Dim strSQL As String
Dim strSku As String
Dim intDbToSearch As Integer
strSku = DLookup("SKUNo", "tblCurrentItem") 'Note: this returns valid SKU#
strSQL = "IF EXISTS(SELECT xxTable.SKUNo "
strSQL = strSQL & "FROM [S:\Our Inventory\Cust Sleeves.mdb].[xxTable] "
strSQL = strSQL & "Where xxTable.SKUNo = " & "'" & strSku & "') Then intDbToSearch = 1"
DoCmd.RunSQL strSQL
This is one of three IF Exists that would run if SKUNo not found in db 1 or 2.
Ultimately intDbToSearch should point to db 1,2,or 3 if SKUNo found or 0 if not.
Thanks
In the end, I pushed usage rules for the 3 databases upstream and can now predetermine which database to search. Thanks again for your input.
Will the sought for SKU always occur in only 1 of the tables?
If you don't want to set table links or use VBA recordsets, only other approach I can see is a query object with a dynamic parameter that references a form control for the SKU input. No idea if this will be faster and will need a query for each remote table.
SELECT SKUNo FROM xxTable IN "S:\Our Inventory\Cust Sleeves.mdb" WHERE SKUNo = Forms!formname!cbxSKU
Then just do DCount on the query.
Dim intDbToSearch As Integer
If DCount("*", "xxQuery") > 0 Then
intDbToSearch = 1
End If
Could UNION the SELECT statements so would have only 1 query object to work with.
SELECT "x1" AS Source, SKUNo FROM xxTable IN "S:\Our Inventory 1\Cust Sleeves.mdb" WHERE SKUNo = Forms!formname!cbxSKU
UNION SELECT "x2", SKUNo FROM xxTable IN "S:\Our Inventory 2\Cust Sleeves.mdb" WHERE SKUNo = Forms!formname!cbxSKU
UNION SELECT "x3", SKUNo FROM xxTable IN "S:\Our Inventory 3\Cust Sleeves.mdb" WHERE SKUNo = Forms!formname!cbxSKU;
How about a simple Function to check if exists by passing the table name and value?
Something like this:
Public Function ExistInTable(Byval TableName As String, ByVal Value As String) As Boolean
ExistInTable = (DCount("*", TableName, "[SKUNo]='" & Value & "'" > 0)
End Function
To call it:
Sub Test()
If ExistInTable("T1", "Whatever") Then 'Exists in T1
If ExistInTable("T2", "Whatever") Then 'Exists in T2
'....
End Sub

How can I select the nth row in MS Access? [duplicate]

This question already has answers here:
How to find 11th entry in SQL Access database table?
(2 answers)
Closed 5 years ago.
I have a MS Access database and I am working on one of its table. When I use the select query order by date, it gives 1000 approx rows. I want to display the 3rd row only. How can I use the select query that provides me with an output of 3rd row only?
nested query would do it, something like this:
declare #table table (id int)
insert into #table values (1),(2),(3),(4),(5)
select top 1 id from
(
select top 3 id from #table
order by id desc
) t
order by t.id asc
Edit: Just noticed you said it was MS-Access, The select query would still be the same
What exactly do you need it for? May be it is reasonable to use some Vba and Dao.Recordset techniques to show the result?
Sub ShowRow()
Dim rs As Dao.Recordset
Dim intFields As Integer
Dim i As Integer
Dim lng As Long
Dim str As String
Set rs = openrecordset("tbl")
rs.movelast
rs.movefirst
intFields = rs.Fields.Count
For lng = 1 To 10
rs.movenext
Next lng
For i = 1 To intFields
str = str & rs(1).Value
Next i
str = Trim(str)
MsgBox str
End Sub

SQL statement for combobox row source

I'm trying to define a SQL statement to use as the Row Source for a ComboBox on an MSAccess form. The SQL should select records from a table tblI where a particular table field matches a variant parameter varS set by the user; however, if varS is Null or not present in another table tblS, the SQl should select all records in tblI.
I can code the first parts of this (varS matches or is null):
SELECT tblI.ID, tblI.S FROM tblI WHERE ((tblI.S = varS) OR (varS Is Null)) ORDER BY tblI.ID;
Where I'm struggling is incorporating the final element (varS not present in tblS). I can code a test for the absence of varS in tblS:
Is Null(DLookup("[tbls.ID]","tblS","[tblS.ID]= " & varS))
but I can't work out how to incorporate this in the SQL statement. Should this work?
SELECT tblI.ID, tblI.S FROM tblI WHERE tblI.S = varS OR varS Is Null OR DLookup("[tbls.ID]","tblS","[tblS.ID]= " & varS) Is Null ORDER BY tblI.ID;
When run as a query it returns every record in tblS no matter the value of varS.
Table structure:
tblI contains 2 fields, Autonumber ID and Long S
tblS contains 1 field, Autonumber ID
My own approach to this problem would be something like this:
Private Sub SetComboSource(vID as Variant)
Dim sSQL as String
sSQL = "SELECT tblI.ID, tblI.S " & _
"FROM tblI "
If IsNull(vID) = False Then
If IsNumeric(vID) = True Then
If DCount("ID", "tblS", "ID = " Clng(vID)) > 0 Then
sSQL = sSQL & "WHERE tblI.S = " & CLng(vID)
End If
End If
End If
sSQL = sSQL & " ORDER BY tblI.ID"
Me.cboComboBox.RowSource = sSQL
End Sub
BTW, I recommend you give your tables and fields more descriptive names and then use aliasing in your SQL, especially for table names. I also think it's best to avoid using Variant variables. I usually use Longs for something like this and I take a value less than 1 to mean that the user didn't select anything, or selected ALL, or whatever meaning you want to derive from it. In other words, my ID's are always a number greater than zero and an ID of less than 1 in a variable means that the ID is empty. Which I use as a signal to create a new record, or to return all records, or whatever meaning you want to derive from it in the given context.
The following should work;
SELECT tblI.ID, tblI.S
FROM tblI
WHERE tbl.ID=varS
OR varS NOT IN(SELECT ID from tblS)

how to check whether the table is empty

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"

Insert all values of a table into another table in SQL

I am trying to insert all values of one table into another. But the insert statement accepts values, but i would like it to accept a select * from the initial_Table. Is this possible?
The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "*" though:
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
-- optionally WHERE ...
I'd better clarify this because for some reason this post is getting a few down-votes.
The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.
You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists.
Try this:
INSERT INTO newTable SELECT * FROM initial_Table
You can insert using a Sub-query as follows:
INSERT INTO new_table (columns....)
SELECT columns....
FROM initial_table where column=value
From here:
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename
There is an easier way where you don't have to type any code (Ideal for Testing or One-time updates):
Step 1
Right click on table in the explorer and select "Edit top 100 rows";
Step 2
Then you can select the rows that you want (Ctrl + Click or Ctrl + A), and Right click and Copy
(Note: If you want to add a "where" condition, then Right Click on Grid -> Pane -> SQL
Now you can edit Query and add WHERE condition, then Right Click again -> Execute SQL, your required rows will be available to select on bottom)
Step 3
Follow Step 1 for the target table.
Step 4
Now go to the end of the grid and the last row will have an asterix (*) in first column (This row is to add new entry). Click on that to select that entire row and then PASTE (Ctrl + V). The cell might have a Red Asterix (indicating that it is not saved)
Step 5
Click on any other row to trigger the insert statement (the Red Asterix will disappear)
Note - 1: If the columns are not in the correct order as in Target table, you can always follow Step 2, and Select the Columns in the same order as in the Target table
Note - 2 - If you have Identity columns then execute SET IDENTITY_INSERT sometableWithIdentity ON and then follow above steps, and in the end execute SET IDENTITY_INSERT sometableWithIdentity OFF
If you are transferring a lot data permanently, i.e not populating a temp table, I would recommend using SQL Server Import/Export Data for table-to-table mappings.
Import/Export tool is usually better than straight SQL when you have type conversions and possible value truncation in your mapping. Generally, the more complex your mapping, the more productive you are using an ETL tool like Integration Services (SSIS) instead of direct SQL.
Import/Export tool is actually an SSIS wizard, and you can save your work as a dtsx package.
I think this statement might do what you want.
INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);
Dim ofd As New OpenFileDialog
ofd.Filter = "*.mdb|*.MDB"
ofd.FilterIndex = (2)
ofd.FileName = "bd1.mdb"
ofd.Title = "SELECCIONE LA BASE DE DATOS ORIGEN (bd1.mdb)"
ofd.ShowDialog()
Dim conexion1 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd.FileName
Dim conn As New OdbcConnection()
conn.ConnectionString = conexion1
conn.Open()
'EN ESTE CODIGO SOLO SE AGREGAN LOS DATOS'
Dim ofd2 As New OpenFileDialog
ofd2.Filter = "*.mdb|*.MDB"
ofd2.FilterIndex = (2)
ofd2.FileName = "bd1.mdb"
ofd2.Title = "SELECCIONE LA BASE DE DATOS DESTINO (bd1.mdb)"
ofd2.ShowDialog()
Dim conexion2 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd2.FileName
Dim conn2 As New OdbcConnection()
conn2.ConnectionString = conexion2
Dim cmd2 As New OdbcCommand
Dim CADENA2 As String
CADENA2 = "INSERT INTO EXISTENCIA IN '" + ofd2.FileName + "' SELECT * FROM EXISTENCIA IN '" + ofd.FileName + "'"
cmd2.CommandText = CADENA2
cmd2.Connection = conn2
conn2.Open()
Dim dA2 As New OdbcDataAdapter
dA2.SelectCommand = cmd2
Dim midataset2 As New DataSet
dA2.Fill(midataset2, "EXISTENCIA")