mySQL :: insert into table, data from another table? - sql

I was wondering if there is a way to do this purely in sql:
q1 = SELECT campaign_id, from_number, received_msg, date_received
FROM `received_txts` WHERE `campaign_id` = '8';
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
VALUES(q1.campaign_id, q1.from_number, q1.received_msg, q1.date_received);
Note: q1 would return about 30k rows.
Is there any way to do what I am attempting above in straight sql?
To just pull the data straight from one table (basically a raw data table) and insert into another table (basically a processed data table)?

INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
SELECT campaign_id, from_number, received_msg, date_received
FROM `received_txts`
WHERE `campaign_id` = '8'

for whole row
insert into xyz select * from xyz2 where id="1";
for selected column
insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:
INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, 'example#domain.xyz', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'
In the above query, there are 2 extra columns named email & current_time.

INSERT INTO Table1 SELECT * FROM Table2

INSERT INTO preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,
uploader_id,is_deleted,last_updated)
SELECT '4827499',pre_image_status,file_extension,reviewer_id,
uploader_id,'0',last_updated FROM preliminary_image WHERE style_id=4827488
Analysis
We can use above query if we want to copy data from one table to another table in mysql
Here source and destination table are same, we can use different tables also.
Few columns we are not copying like style_id and is_deleted so we selected them hard coded from another table
Table we used in source also contains auto increment field so we left that column and it get inserted automatically with execution of query.
Execution results
1 queries executed, 1 success, 0 errors, 0 warnings
Query: insert into preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,uploader_id,is_deleted,last_updated) select ...
5 row(s) affected
Execution Time : 0.385 sec
Transfer Time : 0 sec
Total Time : 0.386 sec

This query is for add data from one table to another table
using foreign key
let qry = "INSERT INTO `tb_customer_master` (`My_Referral_Code`, `City_Id`, `Cust_Name`, `Reg_Date_Time`, `Mobile_Number`, `Email_Id`, `Gender`, `Cust_Age`, `Profile_Image`, `Token`, `App_Type`, `Refer_By_Referral_Code`, `Status`) values ('" + randomstring.generate(7) + "', '" + req.body.City_Id + "', '" + req.body.Cust_Name + "', '" + req.body.Reg_Date_Time + "','" + req.body.Mobile_Number + "','" + req.body.Email_Id + "','" + req.body.Gender + "','" + req.body.Cust_Age + "','" + req.body.Profile_Image + "','" + req.body.Token + "','" + req.body.App_Type + "','" + req.body.Refer_By_Referral_Code + "','" + req.body.Status + "')";
connection.query(qry, (err, rows) => {
if (err) { res.send(err) } else {
let insert = "INSERT INTO `tb_customer_and_transaction_master` (`Cust_Id`)values ('" + rows.insertId + "')";
connection.query(insert, (err) => {
if (err) {
res.json(err)
} else {
res.json("Customer added")
}
})
}
})
}
}
}
})
})

$insertdata="insert into partner_products(partner_id,partner_category_id,main_category_id, inventory_id,partner_product_name, partner_product_brand, partner_product_price,partner_product_quantity,partner_product_unit) select '123',partner_category_id,main_category_id,inventory_id, item_name,brand_name,item_price,item_qty, item_unit from inventory where partner_category_id='1'";

Related

Insert value locating particular column in Microsoft SQL server

I want to insert value locating particular column. I used following script.
"INSERT INTO tbl_user VALUES(UserID = '" + myUser.ID + "', UserName = '" + myUser.Name + "', Password = '" + myUser.Password + "', UserType = '" + myUser.Type + "')";
But it gives me the following error.
Incorrect syntax near '='.
There may some other way to do this task. But I want to do it in this way. Can I?
Always use parameterized query anyway correct your current attempt as below
"INSERT INTO tbl_user (UserID, UserName, UserName , UserType)
VALUES('" + myUser.ID + "','" + myUser.Name + "', '" + myUser.Password + "', '" + myUser.Type + "')";
RECOMMENDED Way is to Go with parameterized query always to prevent SQL Injection Attacks
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_user (UserID, UserName, UserName , UserType)
VALUES (#UserID,...)", connections)
cmd.Parameters.AddWithValue("#UserID", myUser.ID)
...
No, you can't do it your way.
It is:
INSERT INTO table (column1_name,... ) VALUES (column1_value,...) ;
https://www.techonthenet.com/sql_server/insert.php

MS SQL Server (Ver 2008 or above) - How to recreate auto-incremental based in my ID column

I have a table in csv file (with an ID as numeric).
I manually uploaded the information from the file to a SQL Server data table (creating my ID column as numeric).
But, I want to recreate my ID column as autonumeric ID column that continue the number with the latest entry.
Example: the table have the ID 1, 5, 10. I want to recreate the auto-incremental (IDENTITY) ID column (leaving my old ID's) and next row insertion continue with ID 11.
I suppose that doesn't exists a single method to achieve this. But I want to know the steps that I should follow.
Here is a script to give you an idea of one way you can do it.
IF OBJECT_ID('DELETEME.dbo.Tbl') IS NOT NULL
BEGIN
DROP TABLE Tbl
END
IF OBJECT_ID('DELETEME.dbo.stageTbl') IS NOT NULL
BEGIN
DROP TABLE stageTbl
END
CREATE TABLE Tbl (
ID INT
,A CHAR(1)
)
INSERT INTO Tbl VALUES (1,'A'),(2,'B'),(10,'C')
SELECT *
FROM
Tbl
EXEC sp_rename 'DELETEME.dbo.Tbl', 'stageTbl', 'OBJECT'
--renames original table
--create script for the new table
CREATE TABLE Tbl (
ID INT NOT NULL IDENTITY(1,1)
,A CHAR(1)
)
--have to set IDENTITY_INSERT on to insert the ID into an IDENTITY column
SET IDENTITY_INSERT Tbl ON
INSERT INTO Tbl (ID, A)
SELECT ID, A
FROM
stageTbl
SET IDENTITY_INSERT Tbl OFF
DROP TABLE stageTbl
--drops original table
DBCC CHECKIDENT('Tbl', RESEED, 222)
--sets the number you want to with next if you set as 222 the next identity will be 223
INSERT INTO Tbl (A) VALUES ('D')
SELECT *
FROM
Tbl
Basic Steps
Renames original Table (if you want your new table to be the same name as the old, I like to rename first due to auto generated names of constraints etc on the new table)
Create the New table with the Column as an Identity column
Turn on IDENTITY_INSERT
Select all records from the old table into the new one
Turn off IDENTITY_INSERT
You don't have to but you can RESSED the identity to start with whatever number you want otherwise SQL-server will automatically do this based on the greatest ID value.
Drop the original table that you renamed
Thanks to Matt to help me out with the original question.
I want to share a C# method that I used to automate all the necessary steps:
-- Disclaimer: the use of this is my class that connects with MS SQL Server, used to read a SELECT sentence (And returns a DataTable) and Execute SQL Queries, etc. Hope someone could find this code helpfully (AS-IS) --
/// <summary> Recreate an ID with auto-incremental when the table has the ID without this option.
/// <para>Automatically will rename the original table to TABLENAME_TO_DELETE (The process will require copy and recreate the table, then the process will duplicate the information) </para></summary>
/// <param name="strTable">SQL table</param>
/// <param name="strId">ID column</param>
public string recreateIdentityColumn(string strTable, string strId)
{
string strLog = "Table: {0} - ID: {1}".fwFormat(strTable, strId);
string strNewTable = strTable + "_" + fw.rnd(1, 1000).ToString() + fw.rnd(5000, 10000);
DataTable dtTable = this.fillDataTable("SELECT COLUMN_NAME, DATA_TYPE, NUMERIC_PRECISION, NUMERIC_SCALE " +
"FROM Information_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = '" + strTable + "'");
if (!dtTable.fwHasData()) throw new Exception("The current table '" + strTable + "' doesn't exists");
DataRow[] drIdInfo = dtTable.Select("COLUMN_NAME = '" + strId + "'");
if (!drIdInfo.fwHasData()) throw new Exception("The ID column '" + strId + "' doesn't exists in the table '" + strTable + "'");
string strIdType = "";
string strColumns = "";
strIdType = drIdInfo[0]["DATA_TYPE"].fwEmpty("");
if (strIdType.fwContains("decimal"))
strIdType += "({0}, {1})".fwFormat(drIdInfo[0]["NUMERIC_PRECISION"].ToString(), drIdInfo[0]["NUMERIC_SCALE"].ToString());
strLog += "\r\nID DataType: " + strIdType;
foreach (DataRow drInfo in dtTable.Rows)
strColumns += ",[" + drInfo["COLUMN_NAME"].ToString() + "]";
strId = "[" + strId.TrimStart('[').TrimEnd(']') + "]";
strColumns = strColumns.TrimStart(',');
strLog += "\r\nColumns: " + strColumns;
try
{
// Rule 1: Clone the table (Only the structure)
this.executeQuery("SELECT TOP 0 * INTO " + strNewTable + " FROM " + strTable);
// Rule 2: Remove the ID from the clone table
this.executeQuery("ALTER TABLE " + strNewTable + " DROP COLUMN " + strId);
// Rule 3: Add the ID column with the identity property
this.executeQuery("ALTER TABLE " + strNewTable + " ADD " + strId + " " + strIdType + " IDENTITY(1,1)");
// Rule 4: Allow manual insertion of ID in the identity column
this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " ON");
// Rule 5: Copy the rows into the table
int intTotalRows = this.rowCount(strTable);
int intTotalNewRows = this.executeQuery("INSERT INTO " + strNewTable + "(" + strColumns + ") " +
"SELECT " + strColumns + " FROM " + strTable);
strLog += "\r\nOriginal rows {0} - New rows {1}".fwFormat(intTotalRows.ToString(), intTotalNewRows.ToString());
// Rule 6: Return the insertion of identity rows to a normal state
this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " OFF");
// Rule 7: Rename the table with NO IDENTITY as OLD and rename the table with INDENTITY ID as NEW/ACTUAL
this.executeQuery("EXEC sp_rename '" + strTable + "', '" + strTable + "_TO_DELETE', 'OBJECT'");
this.executeQuery("EXEC sp_rename '" + strNewTable + "', '" + strTable + "', 'OBJECT'");
strLog += "\r\nProcess run without problems";
return strLog;
}
catch (Exception ex)
{
strLog += "\r\nException occur";
throw ex;
}
}

SQL two where conditions not working?

I am trying to run this part of code
"UPDATE savedPosts SET liked = 1 WHERE liked <> 1 AND id ='" + idVar + "'"
If I take away the first where condition it works as expected. If I then add the where condition that checks if liked is not equal to 1 it still returns a success. And this always. I dont get it... If 'liked' is set to 1 how can this query be successfull on the second run? And I see it in my db that liked is set to 1 after the first query.
I want different messages shown on the screen for a success and error message. Please help because I tried everything like:
"UPDATE savedPosts SET liked = 1 WHERE (liked <> 1 AND id ='" + idVar + "')"
"UPDATE savedPosts SET liked = 1 WHERE 'liked' <> 1 AND 'id' ='" + idVar + "'"
And variations of both
EDIT
this.storage.query("UPDATE savedPosts SET liked = 1 WHERE liked <> 1 AND id ='" + idVar + "'").then((data) => {
console.log(JSON.stringify(data.res));
}, (error) => {
console.log("ERROR -> " + JSON.stringify(error.err));
});

INSERT OR REPLACE messing with ID SQLite

My app works like this, I have a local database that is filled with data that comes from my API, and when I have a new data inserted in my API the app checks for the last modified item and synchronize it, and in order to achieve that I'm using INSERT OR REPLACE statement, but it is messing up with my "faturamento_id", it is deleting the ids and replacing with new ones, I want it to continue auto increment(if it is possible) when there is new data to synchronize. How can I do that?
angular.forEach(item.faturamentos, function (fat) {
db.transaction(
function (tx) {
tx.executeSql('INSERT OR REPLACE INTO faturamento_pedidos (valor_a_faturar, ' +
'nota_fiscal, ' +
'_criado,' +
'_modificado , ' +
'_status, ' +
'id_rm, ' +
'cod_id, ' +
'id_rm_pedido, ' +
'id_rm_empresa, ' +
'data, ' +
'informacoes_adicionais ) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
[
fat.valor_a_faturar,
fat.nota_fiscal,
fat.criado,
fat.modificado,
fat.status,
fat.id,
fat.cod_id,
fat.id_rm_pedido,
fat.id_rm_empresa,
fat.data,
fat.informacoes_adicionais
]);
},
txErrorHandler,
function () {
log('Record inserted successfully');
}
);
});
TABLE:
tx.executeSql("CREATE TABLE IF NOT EXISTS faturamento_pedidos (" +
"faturamento_id Integer PRIMARY KEY AUTOINCREMENT, " +
"_criado Text, " +
"_modificado Text, " +
"_status Text, " +
"id_rm Integer, " +
"id_rm_pedido Integer, " +
"id_rm_empresa Integer, " +
"cod_id Text, " +
"valor_a_faturar Text, " +
"nota_fiscal Text, " +
"data Text, " +
"informacoes_adicionais Text," +
"CONSTRAINT unique_id_rm UNIQUE ('id_rm'))");
tx.executeSql('CREATE INDEX IF NOT EXISTS "faturamento_pedidos.index_faturamento_id" ON "faturamento_pedidos"("faturamento_id");');
INSERT OR REPLACE always removes the old row, if it exists.
However, there is no reason to use a single SQL statement.
Just try to update the old row, and if it was not found, you know you have to insert a new one:
tx.executeSql("UPDATE ...",
[...],
function(tx, result) {
if (result.rowsAffected == 0)
tx.executeSql("INSERT ...", [...]);
});

Execute all Query or Nothing Should get executed

Well Try to Format Ques.I have set of Queries mentioned below.Now i want to have some functionality which can ensure either all query should execute or not even one(if some kind of error occur) i just want to maintain my database in proper state.
con.setAutoCommit(false);
String qry = "insert into tblAllotment(Employee_ID,Employee_Name,Area,Building_Name,Flat_Type,Flat_No,Date_Application,Date_Allotment,Admin_Code) values(" + id + ",'" + name[1] + "','" + area + "','" + flat[2] + "','" + flat[1] + "','" + flat[0] + "','" + dte + "','" + date + "'," + uid + ")";
String qry1 = "insert into tblFlat_Report(Flat_No,Area_Code,Employee_ID,Date_Allottment,Admin_Code)values('" + flat[0] + "'," + acode + "," + id + ",'" + date + "'," + uid + ")";
//String qry2="UPDATE tblUser_Report t1 JOIN (SELECT MAX(S_Date) s_date FROM tblUser_Report WHERE Employee_ID = "+id+") t2 ON t1.s_date = t2.s_date SET t1.Status = 'A', t1.S_Date ='"+date+"' WHERE t1.Employee_ID ="+id+"";
String qry2 = "insert into tblUser_Report(Employee_ID,Employee_Name,S_Date,Area,Status) values(" + id + ",'" + name[1] + "','" + date + "','" + area + "','A')";
String qry3 = "update tblFlat set Status ='A' where Flat_No='" + flat[0] + "' AND Area_Code=" + acode + " ";
String qry4 = "update tblUser set WL_Flag='N' where Employee_ID=" + id + "";
st = con.createStatement();
int i = st.executeUpdate(qry);
int j = st.executeUpdate(qry1);
int k = st.executeUpdate(qry2);
int l = st.executeUpdate(qry3);
int m = st.executeUpdate(qry4);
con.commit();
if (i != 0 & j != 0 & k != 0 & l != 0 & m != 0) {
Done = "Data Inserted Successfully...!!!";
} else {
System.out.println("Error Occured");
}
} catch (SQLException e) {
con.rollback();
System.out.println(e.getMessage());
}
}
Your database has to provide transactions. If you use MySQL, you cannot use a MyISAM database table, you have to use a InnoDB one (for example).
You begin a transaction at the start of your code, then check each result. If you get an error, you issue a rollback. If everything runs fine, you issue a commit at the end.
Your look should look like:
con.setAutoCommit(false); // at the beginning, to prevent auto committing at each insert/update/delete
// ... your updates, with error checking
con.commit(); // at the end, only if everything went fine.
In case of error, call con.rollback()
Wrap your queries in try catch. Add setAutoCommit(false) at the start of try and commit() at its end, add rollback() in catch block.
try {
conn.setAutoCommit(false);
// Execute queries
conn.commit();
}
catch (SQLException e) {
conn.rollback();
}