What's the best way to extract data from a database with an update if needed? - sql

I need to insert a data into a DB using query like this one:
INSERT INTO Table1
(aID)
VALUES
(select aID from Table2 where aID="aID"))
The problem is that if Table2 doesn’t have the aID I need to update it with it and extract the newly created ID. Is there a SQL command that automatically does it?

Your question is kinda all over the map...
The problem is that if Table2 doesn’t have the aID I need to update it with it - what do mean by this?
If it doesn't exist you got to insert it ...rght?
Having said that, you need to write a stored-procedure to achieve your objective...and also set "aID"...to be an auto-incremental,seeded Identifier column type
Let me know if you need elaboration

Presumably, you have more columns to add in the real query, as it doesn't make any sense at the moment, you just have one column in the whole thing.
Presuming that you want to insert some other columns from table 2 into table 1 and then update into table 2 the new id that comes from the table 1, there's no one command that will do this for you.
Something like (in SQL Server)
DECLARE #newId int
insert into table1 (.. columns..) values select (..columns..) from Table2 where aID="aID")
select #newId=scope_identity()
update table2 set foreign_key_column_to_table_1=#newId where aID="aID"

Related

Why is 'insert into select' statement in SQL inserting as a new row and not inserting correctly?

I have table 1.
I have another empty table 2 with the following columns.
I want to insert into table 2 by selecting from table 1 - so I write the query as:
insert into table2(employee,id,zone,url)
select employee, id, zone, concat('https://',employee,'.com/',id,'?',zone)
from table1
Now my table 2 looks like this,
Now for the authcode column, I do the following and insert it into the table2.
insert into table2(authcode)
SELECT CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)
from table2.
But the insert happens differently like this AS AN ENTIRE NEW SET OF ROWS.
Can someone help me to insert the last column to the corresponding rows instead of it creating a new one?
What you should be doing is UPDATE the table to fill the column authcode, but you could do it all in 1 step while you are inserting the rows:
insert into table2(employee,id,zone,url, authcode)
select
employee,
id,
zone,
concat('https://',employee,'.com/',id,'?',zone),
CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(concat('https://',employee,'.com/',id,'?',zone),8,100)),2)
from table1
or if you want to update:
update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)
where authcode is null
The result you are seeing is the intended behavior for an INSERT statement. It will always insert new rows.
If you want to modify existing rows your need to use an UPDATE statement.
You can either modify your INSERT to look like what #forpas has posted to get all this work done in one step. Another option is to modify the second INSERT to be an UPDATE like the following:
update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)

How to delete specific column values in multiple "insert into" query

Sorry if you think my question is too basic, because i'm a newbie.
Lets say i have 1000 lines of query like this
INSERT INTO table (column1,column2,column3) VALUES (1,2,3);
INSERT INTO table (column1,column2,column3) VALUES (3,33,333);
....
I want to delete column2 with its value, Is there any way so that i dont need to delete 1000 rows manualy. Thanks.
Perhaps you want to completely drop the second column:
ALTER TABLE yourTable DROP COLUMN column2;
Although you may have used many statements to build up the data in your table, dropping a particular column only requires a one-liner.

how can I get a variable with all the results and iterate over it?

I have a table with some records, about 40, called Table1.
I would like to create a new register in another table for each these records, but I don't know how can I do it. I would like to iterate with a while loop for each record and insert the record in the other table, but I don't how (the syntax).
I would like something like this:
foreach record in myTable1
Insert into Table2(IDTable1) VALUES(record.IDTable1)
end foreach
I don't know scripts in SQL Server.
Thanks.
If you have only insertion, you can do this:
INSERT INTO Table2 (IDTable1)
SELECT IDTable1 FROM myTable1
It will select all IDTable1 from myTable1 and insert them into Table2.
SQL Server, for the most part, is set-based. That means that queries and rows are down in sets, group and filtered by clauses. Only in rare cases will you want or need to iterate over every single row in a result set and do something with it.
I'd say in your case, you're wanting to copy the contents of one table to another. You can do that several ways, but one of the easiest is something like this:
SELECT
IDTable1
INTO
Table2
FROM
Table1
This assumes that Table2 does not exist, and will create it. If Table2 already exists, your syntax will change to be like what other answers indicated:
INSERT INTO Tabel2( IDTable1 )
SELECT
IDTable1
FROM
Table1

How to Update a Single record despite multiple Occurances of the same ID Number?

I have a table that looks like the below table:
Every time the user loan a book a new record is inserted.
The data in this table is derived or taken from another table which has no dates.
I need to update this tables based on the records in the other table: Meaning I only need to update this table based on what changes.
Example: Lets say the user return the book Starship Troopers and the book return is indicated to Yes.
How do I update just that column?
What I have tried:
I tried using the MERGE Statement but it works only with unique rows of data, meaning you get an error if the same ID appears more than once.
I also tried using a basic UPDATE Statement and a JOIN but that's not going well.
I am asking because I have ran out of ideas.
Thanks for reading
If you need to update BooksReturn in target table based on the same column in source table
UPDATE t
SET t.booksreturn = s.booksreturn
FROM target t JOIN source s
ON t.userid = s.userid
AND t.booksloaned = s.booksloaned
Here is SQLFiddle demo
You can do this by simple Update & Insert statement.....
Two table A & B
From B you want to insert data into A if not exists other wise Update that data....
,First Insert into temp table....
SELECT *
INTO #MYTEMP
FROM B
WHERE BOOKSLOANED NOT IN (SELECT BOOKSLOANED
FROM A)
,Second Check data and insert into A.
INSERT INTO A
SELECT *
FROM #MYTEMP
And at last write one simple update statement which update all data of A. If any change then it also reflect to that data otherwise data as it is.
You can also update from #MYTEMP table.

How to update multiple rows in the same table of MySQL with PHP?

If only one row with a distinct field is to be updated,I can use:
insert into tab(..) value(..) on duplicate key update ...
But now it's not the case,I need to update 4 rows inside the same table,which have its field "accountId" equal to $_SESSION['accountId'].
What I can get out of my mind at the moment is:
delete from tab where accountId = $_SESSION['accountId'],
then insert the new rows.
Which obviously is not the best solution.
Has someone a better idea about this?
Use the update just like that!
update tab set col1 = 'value' where accountId = $_SESSION['accountId']
Moreover, MySQL allows you to do an update with a join, if that makes your life a bit easier:
update
tab t
inner join accounts a on
t.accountid = a.accountid
set
t.col1 = 'value'
where
a.accountname = 'Tom'
Based on your question, it seems like you should review the Update Statement.
Insert is used to put new rows in - not update them. Delete is used to remove. And Update is used to modify existing rows. Using "Insert On Duplicate Key Update" is a hackish way to modify rows, and is poor form to use when you know the row is already there.
load all of the values in to a temporary table.
UPDATE all of the values using a JOIN.
INSERT all of the values from the temp table that don't exist in the target table.
You can use replace statement. This will work as a DELETE followed by INSERT