I have 30 different tables in my database in every tables has same column name "res_ret"=define as 0 in every tables. I want to Update and Set res_ret value=1 . This is my code and this is work. How can I do this in dynamic codings. Thanks in Advance :)
conn.Open()
sql = "Update table_1 SET res_ret= 1"
cmd.CommandText = sql
cmd.Connection = conn
cmd.ExecuteNonQuery()
sql = "Update table_2 SET res_ret=1"
cmd.CommandText = sql
cmd.Connection = conn
cmd.ExecuteNonQuery()
sql = "Update table_3 SET res_ret=1"
cmd.CommandText = sql
cmd.Connection = conn
cmd.ExecuteNonQuery()
conn.Dispose()
conn.Close()
As #TimSchmelter points out, there is probably a better way of doing this, but:
VB.NET
Dim tableList = { "table_1", "table_2", "table_3" }
For Each tableName As String In tableList
cmd.CommandText = String.Format("update {0} set res_ret = 1", tableName)
cmd.ExecuteNonQuery()
Next
c#
var tableList = new List<string> { "table_1", "table_2", "table_3" ... };
foreach(var tableName in tableList) {
cmd.CommandText = string.Format("update {0} set res_ret = 1", tableName);
cmd.ExecuteNonQuery();
}
Finally This Codes Work ..
Dim tableList = {"table_1", "table_2", "table_3"}
For Each tableName As String In tableList
conn.Open()
cmd.CommandText = String.Format("update {0} set res_ret = 1", tableName)
cmd.Connection = conn
cmd.ExecuteNonQuery()
conn.Dispose()
conn.Close()
Next
Related
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0))
end with
The value from the datagrid view contains an apostrophe where I get an error in ('s). Any work around with this?
EDIT:
This is the error:
SqlException was unhandled. Incorrect syntax near 's'.
EDIT 2: i've revised the code to this:
for 1=0 to datagridview.rows.count -1
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0).value)
end with
con.Close()
con.Open()
If Not cmd.ExecuteNonQuery() > 0 Then
con.Close()
Exit For
End If
next
Error is still the same.
As it goes through all the values quickly in one go, I would make the connection once and change the value of the parameter for each iteration, like this:
Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(#sc)"
Using conn As New SqlConnection("your connection string"),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#sc",
.SqlDbType = SqlDbType.NVarChar,
.Size = -1})
conn.Open()
For i = 0 To dgv.Rows.Count - 1
Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
cmd.Parameters("#sc").Value = tname
cmd.ExecuteNonQuery()
Next
End Using
Including the size of the parameter in its declaration helps SQL Server keep things tidy (it only needs one entry in the query cache).
The Using statement makes sure that the connection and command are disposed of properly when they are finished with.
The purpose of checking If Not cmd.ExecuteNonQuery() > 0 was not clear to me, so I didn't put that in.
(I used "dgv" as the name of the DataGridView.)
Try to replace the " ' " by " '' "
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", replace(sc.cells(0), "'", "''")
end with
/**** EDIT ****/
I will consider by the way that your code have a problem with the affectation of the value. You get the value into SC then try to get again the value from cell
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters("#sc").value = sc.replace("'", "''")
end with
I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
I'm inserting into a table that has 2 columns that trigger values upon inserting into the table.
I'm trying to get those 2 returns back and the only things I'm getting back is a string of "ReturnValue"
Dim query As String = "insert into SHOP_HEADER (CATEGORY, DESCRIPTION, CONSUMABLE) values (?,?,?) RETURNING SI_KEY, PART_NO INTO :VAR_SI, :VAR_PART"
Using Conn As New OleDbConnection(ConnectionStringToORACLE)
Using CMD As New OleDbCommand()
With CMD
.Connection = Conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("CATEGORY", ListBox.SelectedValue)
.Parameters.AddWithValue("DESCRIPTION", txtDescription.Text)
.Parameters.AddWithValue("CONSUMABLE", "0")
.Parameters.AddWithValue("SI_KEY", ParameterDirection.ReturnValue)
.Parameters.AddWithValue("PART_NO", ParameterDirection.ReturnValue)
End With
Conn.Open()
CMD.ExecuteNonQuery()
VAR_SI = (CMD.Parameters("SI_KEY").Value.ToString)
VAR_PART = (CMD.Parameters("PART_NO").Value.ToString)
End Using
End Using
VAR_SI and VAR_PART then = "ReturnValue"
I've also tried changing SI_KEY and PART_NO to VAR_SI and VAR_PART in CMD.Parameters and .Parameters.AddWithValue as well with the same result.
UPDATE WORKING
Here's what I ended up doing and it works now.
Dim SIparam As New OleDbParameter()
SIparam.ParameterName = "VAR_SI"
SIparam.DbType = System.Data.DbType.Int32
SIparam.Direction = System.Data.ParameterDirection.Output
Dim PARTparam As New OleDbParameter()
MTIparam.ParameterName = "VAR_PART"
MTIparam.DbType = System.Data.DbType.Int32
MTIparam.Direction = System.Data.ParameterDirection.Output
Dim query As String = "insert into SHOP_HEADER (CATEGORY, DESCRIPTION, CONSUMABLE) values (?,?,?) RETURNING SI_KEY, PART_NO INTO :VAR_SI, :VAR_PART"
Using Conn As New OleDbConnection(ConnectionStringToORACLE)
Using CMD As New OleDbCommand()
With CMD
.Connection = Conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("CATEGORY", ListBox.SelectedValue)
.Parameters.AddWithValue("DESCRIPTION", txtDescription.Text)
.Parameters.AddWithValue("CONSUMABLE", "0")
.Parameters.Add(SIparam)
.Parameters.Add(MTIparam)
End With
Conn.Open()
CMD.ExecuteNonQuery()
VAR_SI = (SIparam.Value)
VAR_PART = (MTIparam.Value)
End Using
End Using
I have this table-valued function in my SQL Server 2008 database:
Create FUNCTION dbo.fct1(#Code varchar(10) )
RETURNS TABLE
AS
RETURN
(
select CODE , NOM
from CODIF
where NUMERO = 'TP'
and CODE = #Code
)
When I call it from my code :
sSQL = "select * from fct1(" & Code & ")"
Dim cmd As New SqlCommand(sSQL, Connection)
If Connection.State <> ConnectionState.Open Then Connection.Open()
Dim rd As SqlClient.SqlDataReader
rd = cmd.ExecuteReader()
I get this error :
column name not valid : 'EA2'
I need to know :
What is the reason of this error?
How can I fix it?
You're missing the ' from the sql.
You should probably parameterise the SQL and try to use using as well:
using conn as new sqlconnection(connstring), comm as new sqlcommand("",conn)
conn.open()
comm.commandtype = commandtype.text
comm.commandtext = "select * from fct1(#Code)"
comm.parameters.addwithvalue("#Code",Code)
Dim rd as sqldatareader = comm.executedatareader
end using
Missed '
sSQL = "select * from fct1('" & Code & "')"
Dim cmd As New SqlCommand(sSQL, Connection)
If Connection.State <> ConnectionState.Open Then Connection.Open()
Dim rd As SqlClient.SqlDataReader
rd = cmd.ExecuteReader()
How would you get the last Primary Key/Auto Increment value in a table using OleDb?
I need to get this value so I can create a folder for a record before it is added so that files can be copied to the folder when it is added.
Any idea?
I have tried as following.
##Identity 'Need to insert a record first and I can't do that without copying the files first
SELECT SCOPE_IDENTITY() 'Doesn't work with OleDb
This is the error message I get:
I think this might work:
SELECT MAX(ID) FROM MyTable
you can do it like this because of The Jet 4.0 provider supports ##Identity,
Reference
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
Try this
Select IDENT_CURRENT('TableName')
It Will retrun Last ID(If it's Auto increment) of your Table
reference
**c#**
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
**VB**
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
refer
You can try Check if NULL first :
Select if(IsNull(Max(ColName)),1,Max(ColName) + 1 ) From YourTable
try this (vb.net)
'''
Dim lastrecord As Integer
Dim command As New SqlCommand("Select IDENT_CURRENT('tbluom')+1", conn)
command.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(command)
lastrecord = command.ExecuteScalar()
txt_uomid.Text = lastrecord
MsgBox(lastrecord)
Dim encode As String = txt_uomid.Text '"99999"
Dim encint As Integer = Integer.Parse(encode) '+ 1
encode = "00" & "-" & encint.ToString("00000").Substring(1, 4)
MsgBox(encode)
''''