Combining 2 insert into in one command - insert-into

I couldn't figure this out:
I want to add a row in a table-a and 3 columns of this row will come from table-b and other 2 columns will come from e.g textboxes...
This code didn't work...
SqlCommand cmd35 = new SqlCommand("INSERT INTO BTmr (Barcode,[Machine Name],[Machine ID]) SELECT Barcode,[Machine Name],[Machine ID] FROM BkmP WHERE barcode like '" + c13 + "%' UNION INSERT INTO BTmr([Repair Cost],[Repair Date],Barcode)values (#cst,#rprd)", connection);
cmd35.Parameters.AddWithValue("#cst", textBox10.Text);
cmd35.Parameters.AddWithValue("#rprd", dateTimePicker1.Text);

Just put the parameters as static values in the select statement.
SqlCommand cmd35 = new SqlCommand("INSERT INTO BTmr (Barcode,[Machine Name],
[Machine ID],[Repair Cost],[Repair Date]) SELECT Barcode,[Machine Name],
[Machine ID],#cst AS [Repair Cost],#rprd AS [Repair Date] FROM BkmP WHERE
barcode like '" + c13 + "%', connection);
cmd35.Parameters.AddWithValue("#cst", textBox10.Text);
cmd35.Parameters.AddWithValue("#rprd", dateTimePicker1.Text);
While your're at it, parameterize that where clause: https://stackoverflow.com/a/251380/123422

Related

Force Short TextField To Always Be X Characters

I am attempting to use a IIF() statement in a query to update a short text field to always be 4 characters. This is my syntax, but
SELECT DISTINCT IIf(Len([User ID] = 1), "000" & [User ID], IIf(Len([User ID] = 2), "00" & [User ID], IIf(Len([User ID] = 3), "0" & [User ID], [User ID]))) AS ST
FROM _TestData;
However it seems to be appending 0's to the data regardless of length?
It could be this simple:
SELECT DISTINCT Right("000" & [User ID], 4) AS ST
FROM TestData;
If [User ID] is number, try this:
SELECT DISTINCT Format([User ID], "0000") AS ST
FROM _TestData;
Update
Missed that the field is short text. In this case
SELECT DISTINCT Format(CLng(Nz([User ID],0)), "0000") AS ST
FROM _TestData;

Passing values to the insert query with select query

I want to insert two values in the a table.One of which is actually taken from another table with the select statement as below.
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES(SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "',#allowance_id_fk)";
There is syntax error exception as shown in the figure.
Your SQL statement is invalid. Use the following:
query = "INSERT INTO empallowance SELECT emp_id, #allowance_id_fk FROM employee WHERE emp_cnic='" + cnic + "'";
You can read all about the approach here.
you have to use bracket in sub query.
try this:
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES((SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "'),#allowance_id_fk)";
You can modify your query as below :
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) SELECT emp_id, #allowance_id_fk FROM employee WHERE emp_cnic= ' " + cnic + "'";
Add '()' between select query for a separation of insertion query.
INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES((SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "'),#allowance_id_fk)
You can't do it that way but you can create a select statement and insert its results:
"INSERT INTO empallowance (emp_id_fk,allowance_id_fk)
select emp_id, #allowance_id_fk
from employee
WHERE emp_cnic='" + cnic + "'"
Also, take note, using string concatenation to insert the parameter is vulnerable for SQL Injections - Use parameterized queries instead
You can easily do this by this, it worked for me
query = "INSERT into TABLE1 (name,city)
Select name, 'Paris' from TABLE2 where id = 1";
you can assign values directly in a select query.

MySqlDataReader reads data when there is sum(a+b) in the query

When I use this query
("SELECT id, at_date AS MyDate , nom, pax, SUM(prix*pax) AS somme,
SUM(pax) AS totpax
FROM atelier ORDER BY " + Order_by + " " + SortDir + " LIMIT #Myid," +
PublicVariables.MySqlLimit, conn)
This gives an error here
_listBox[1].Items.Add(Convert.ToDateTime(reader["MyDate"]).ToString("d"));
Because there is NO ROWS int the table. Table is EMPTY.
But when I supress SUM(prix*pax) AS somme and SUM(pax) AS totpax from the query, reader does not read and no error occurs.
Is there any trick of MySql in there ?
I resolved the probleme by checking the table if there is any rows before calling this method but it's not what I like any idea ?
Use Group by clause for all non aggregate function before order by clause:
group by id,MyDate,nom,pax

Very Strange error when trying to INSERT into a database with more than 1 entry

HOPEFULLY.....the title makes sense. But basically this is what is going on. I'm creating a form where a user will be able to View, Update, Insert and Delete records from tables within a database.
I'm using a combo box to display the table data:
Now If I try to Insert a new record, it works fine, until I try and more than one.
This is me placing just the personID record in. and it works fine:
But if i try and add a personID AND a firstName this happens:
as you can see, it ignores the personID entry, and just goes for the firstName.
I cant go further in my code without figuring out what is causing me to not be able to put in 2 things at once.
Here is my INSERT code:
string myInsertSQL;
myInsertSQL = "INSERT INTO person(";
myInsertSQL += "personID)";
myInsertSQL += " VALUES ('";
myInsertSQL += personID.Text + "')";
myInsertSQL = "INSERT INTO person(";
myInsertSQL += "firstName)";
myInsertSQL += " VALUES ('";
myInsertSQL += firstName.Text + "')";
MySqlConnection conn = new MySqlConnection(connstring);
MySqlCommand cmd = new MySqlCommand(myInsertSQL, conn);
With the above, it will only insert the firstName.
I have no idea why this would happen, and I would love some input. Thanks!
By doing this, the DB would insert the ID and the firstname on 2 distinct rows, if you didn't overwrite the first string (myInsertSQL = "INSERT INTO person(";). Here, it only performs the second query (i.e. inserting first name).
Try:
myInsertSQL = "INSERT INTO person(";
myInsertSQL += "personID, FirstName)";
myInsertSQL += " VALUES ('";
myInsertSQL += personID.Text + "', '"+ firstName.Text +"')";
Please note that this is wide open to SQL injections. Try to use prepared statements instead of directly injecting plain text into queries:
string myInsertSQL = "INSERT INTO person(personID, firstName) VALUES (#personID, #firstName)";
MySqlCommand cmd = new MySqlCommand(myInsertSQL, conn);
cmd.Parameters.AddWithValue("#personID", personID.Text);
cmd.Parameters.AddWithValue("#firstName", firstName.Text);
EDIT :
According to your comment, you try to insert more than those 2 values. This work the same.
The error says that you did specify a different number of values and fields. You speak of 6 values, but only list 5 (personID, firstName, address, phoneNumber, postCode). I suspect you forgot the lastName:
string myInsertSQL = "INSERT INTO person(personID, lastName, firstName, address, phoneNumber, postCode) ";
myInsertSQL += "VALUES (#personID, #lastName, #firstName, #address, #phoneNumber, #postCode)";
MySqlCommand cmd = new MySqlCommand(myInsertSQL, conn);
cmd.Parameters.AddWithValue("#personID", personID.Text);
cmd.Parameters.AddWithValue("#lastName", lastName.Text);
cmd.Parameters.AddWithValue("#firstName", firstName.Text);
cmd.Parameters.AddWithValue("#address", address.Text);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber.Text);
cmd.Parameters.AddWithValue("#postCode", postCode.Text);
// and so on...
myInsertSQL = "INSERT INTO person(";
here you completely overwrite the myInsertSQL String, so whatever you put in there before is gone before you even send it to the database.
You are overwriting variable value
myInsertSQL += personID.Text + "')";
myInsertSQL = "INSERT INTO person(";

SQL table accepting same names again and again database name checking

I am trying to insert the guestpass type name in table guestpasstypes and at a time it will check the database whether the database has already that name or not by using this statement:
#"INSERT INTO guestpasstypes(guestPasstype_Name)values('" + tbPassType.Text + "') where not exists (select 'guestPasstype_Name' from guestpasstypes where guestPasstype_Name = '" + tbPassType.Text + "')"
but it accepts the duplicate name too, and it does not work. Would anyone please help on this?
For SQL Server it would look like this.
insert into guestpasstypes (guestPasstype_Name)
select 'name1'
where not exists (select *
from guestpasstypes
where guestPasstype_Name = 'name1')
I think it should work for MySQL as well.
If you are on SQL Server 2008 you can use MERGE.
merge guestpasstypes as G
using (select 'name2') as S(Name)
on G.guestPasstype_Name = S.Name
when not matched then
insert (guestPasstype_Name) values (Name);
UPDATE
I think the first option could be applied to your problem like this:
#"INSERT INTO guestpasstypes(guestPasstype_Name) select '" + tbPassType.Text
+ "' where not exists (select * from guestpasstypes where guestPasstype_Name = '"
+ tbPassType.Text + "')"
If you want it to throw an error you can either :
Put a unique index on the column (the easiest and preferred way)
or
Write a stored procedure which returns an error flag. Within the procedure, you first check for a matching value and if one is found, set the error flag and return. Otherwise do the insert as normal.
Try either INSERT IGNORE or INSERT ON DUPLICATE KEY:
INSERT IGNORE INTO `guestpasstypes`(`guestPasstype_Name`) values('" + tbPassType.Text + "');
OR
INSERT INTO `guestpasstypes`(`guestPasstype_Name`)values('" + tbPassType.Text + "') ON DUPLICATE KEY UPDATE `guestPasstype_Name` = `guestPasstype_Name`;