InsertStatement using SelectStatement in asp.net - sql

I am trying use insert but as one of parameters use result of select statement
try {
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RentCarConnectionString"].ConnectionString);
conn1.Open();
string selectQuery = "Select IDOsoby from Klienci Where Email = #Semail ";
string insertQuery = "insert into Wypozyczenia (IdOsoby, IDCAR, DataWypozyczenia) values (#idOs, #idcar, #data)";
string updateQuery = "Update Samochody SET CzyDostepny = 'False' Where IDCAR = #idCar";
SqlCommand com1 = new SqlCommand(selectQuery, conn1);
SqlCommand com2 = new SqlCommand(insertQuery, conn1);
SqlCommand com3 = new SqlCommand(updateQuery, conn1);
com1.Parameters.AddWithValue("#Semail", Session["New"]);
com2.Parameters.AddWithValue("#idOs", selectQuery);
com2.Parameters.AddWithValue("#idCar", Session["S_polka"]);
com3.Parameters.AddWithValue("#idCar", Session["S_polka"]);
com2.Parameters.AddWithValue("#data", DateTime.Today.ToShortDateString());
com1.ExecuteNonQuery();
com2.ExecuteNonQuery();
com3.ExecuteNonQuery();
conn1.Close();
}
catch(Exception ex)
{
}
Code working but into Wypozyczenia table It has been added IdOsoby as "It has been added". Please help how can I fix it ?

By this way, Combine the separate Insert and Select queries. Just use Insert into..Select syntax
insert into Wypozyczenia (IdOsoby, IDCAR, DataWypozyczenia)
Select IDOsoby, #idcar, #data from Klienci Where Email = #Semail

Related

System.Data.SqlClient.SqlException: Incorrect syntax near "="

I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.

Use sql table like sql parameter in vb.net

I have query with sql parameters. My parameter must be my table from database and I don't now how I can realize this.
I did it so:
myCommand = myConnection.CreateCommand()
myCommand.CommandType = CommandType.Text
myCommand.CommandText =
"SELECT Id, Bez, Param5, Info from Table" & "#idFixed"
myCommand.Parameters.Add("#idFixed", SqlDbType.VarChar).Value = strIdFixed
strIdFixed(transmitted parameter) must be something id, because I have many tables with names Table01, Table02, Table333 ....
I have it
Dim tableName As String = "Test" + strIdFixed.ToString.Trim
Dim builder = New SqlCommandBuilder()
Dim escapedTableName As String = builder.QuoteIdentifier(tableName)
myCommand = myConnection.CreateCommand()
myCommand.CommandType = CommandType.Text
myCommand.CommandText =
"SELECT Id, Bez, Param5, Info from " + escapedTableName
Thank https://stackoverflow.com/a/17948039/6787667

How to Query multiple tables dynamically VB.NET

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

How to get last auto increment value in a table? VB.NET

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)
''''

Select SCOPE_IDENTITY not executing after insert statement;

I try to get the id of the last inserted t ouristin the table as I put Selct SCOPE_IDENTITY; after the insert query.
The problem is that when I try to show the id of the inserted tourist in the label - just nothing happens. (only the insert query is executed);
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += "VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir);Select SCOPE_IDENTITY()";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir",tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir",tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir",tx888_2.Text);
int added = 0;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
if (added > 0)
{
lblproba.Text+=added.ToString();
}
}
catch (Exception ex)
{
//lblResult.Text = ex.Message;
}