SQL Command to copy data from 1 column in table and 1 column in another table into a new table? - sql

I had to make a new table to get the Include statement working in Entity Framework since EF was looking for a table called be_PostTagbe_Posts. I was using EF Code First from DB. But now the question is about SQL. I added one row of data and now the include works. But what I am looking for is a SQL command that can copy data from 1 column in 1 table and 1 column in another into the new be_PostTagbe_Posts table. In the be_Posts table I need the data in PostRowID to go into be_Posts_PostRowID and PostTagId to go into be_PostTag_PostTagID. Both be_PostTag_PostTagID and be_Posts_PostRowID are in the new be_PostTagbe_Posts table. I am not very good with SQL so not sure how to do this.
Edit: Thanks for the answers. I tried 2 separate queries but only data was inserted into the the be_PostTag_PostTagID while be_PostTag_PostRowID remained null.
And I tried this query which returned The multi-part identifier "be_PostTag.PostID" could not be bound.
INSERT INTO be_PostTagbe_Posts(be_PostTag_PostTagID, be_Posts_PostRowID)
SELECT be_PostTag.PostTagID, be_Posts.PostRowID
WHERE be_PostTag.PostID = be_Posts.PostID
EDIT:
This only inserted half the data - even 2 inserts leave one column null
INSERT INTO be_PostTagbe_Posts (be_Posts_PostRowID)
SELECT PostRowID FROM be_Posts;
INSERT INTO be_PostTagbe_Posts (be_PostTag_PostTagID)
SELECT PostTagID FROM be_PostTag;
And yet management studio tells me the query executed successfully but one column is still null. Weird.
Here are screenshots of the tables:

SELECT PostTagID AS be_PostTag_PostTagID, PostRowID AS be_Posts_PostRowID
INTO be_PostTagbe_Posts
FROM be_PostTag
Inner JOIN be_Posts
ON be_PostTag.PostID=be_Posts.PostID
That command created the new table with the 2 columns populated.

If i understand you ,you want to Copy Table Z's Column A to Table X And Table Z's Column B to Table Y.
If it is so, According to your question it is not clear about Table Structure of TableX and TableY
Assuming TableX And TableY to single ColumnTable [Apart from IdentityColumn] our query will be
INSERT INTO TableX
SELECT ColumnA FROM TableZ
INSERT INTO TableY
SELECT ColumnB FROM TableZ
Rest put your Entire Structure of Table To Get More Help Because These query are on Assumptions

There's not enough information in your question to give you a working example, but this would be the general syntax for INSERTing into a different table using a query SELECTing from two other tables.
INSERT INTO destination_table(wanted_value_1, wanted_value_2)
SELECT table_1.source_field_1, table_2.source_field_1
WHERE table_1.matching_field = table_2.matching_field
There has to be some sort of relationship between the two tables for the WHERE clause to work in that statement. I'm guessing based the little information you provided that there is a PostRowID field somewhere in the table that contains the tags such that your data would look similar to this in the tag table:
PostRowID PostTagID
--------- ---------
1 1
1 2
1 3
1 4
2 1
2 2
3 3
4 4

It sounds like you should use two sql statements:
Insert into `be_PostTagbe_Posts` (`be_PostTag_PostTagID`)
select `PostTagID` from POSTTAGIDTABLE
and
Insert into `be_PostTagbe_Posts` (`be_Posts_PostRowID`)
select `PostRowID` from POSTTAGIDTABLE
unless the items have some sort of relationship, then if you have a select statement that will select the merged data in two columns you can just do
Insert into `be_PostTagbe_Posts` (`be_PostTag_PostTagID`,`be_Posts_PostRowID`)
(select statement that selects the two items)

Related

insert and update from table a to table b by combining 2 column from table a in postgres

I have 2 tables name Table A and Table B
"Table A has 10 columns named ta1, ta2, ta3...ta10"
"Table b has 2 columns name id (PK,AI) and tb1"
My requirement is to combine "ta3" and "ta4" from table A initially,
or it will check for the "tb1" column whether any same data is available, if available do nothing else insert the new data.(if a new row is added in the ta3 or ta4, it should be added to the 2nd table column named tb1)
I have checked other functions in the for combining the data from ta3 and ta4 by using the "unnest" function, but if I use that, I'm getting stuck in the insert, as it will insert on each query rather than checking whether any data is there or not.
any solution on this legends.
simply I just want to combine 2 column from 1st table and store it in a column on 2nd table, but in 2nd table's column it should be only distinct values taken from both of those 1st table columns. this should automatically check for the values in the column of 2nd table and compare that with the new one and if there is change the insert else neglect. I hope my question is clear.
Table1
Table 2
new table-1
Expected table-2

How to get list of deleted records in SQL

My goal is to separate two types of data in table that is being sent to a stored procedure. In this table, I will have two kinds of records of type 1 and type 2, let's say.
I want to delete all data of type 2 from the inputted table but still have it stored in a separate temp table.
I know how to delete data with the following statement:
DELETE t
FROM #tags t
WHERE t.Type = 2
Is there a way to retrieve the deleted records so I can insert them into a separate temp table?
Otherwise I will have to have a separate code block before that looks like the following:
INSERT #dynamicTags(String)
SELECT String
FROM #tags t
WHERE t.Type = 2
Any ideas to combine the two above statements into one?
If using SQL Server you can do this with the OUTPUT clause:
DELETE t
FROM #tags t
OUTPUT DELETED.* INTO #MyTableVar
WHERE t.Type = 2
If you are using postgres you can use the returning clause:
http://www.postgresql.org/docs/9.3/static/sql-delete.html

access 2010 append data into table without overwriting existing records

Sorry for the long question/post but need some help as I've been searching for several days but havent found anything that helps. Seems like it should be easy but..here goes
I have table1 in my (Access 2010) database that has exising records. I have another table2 that after I run a query, it first deletes the data in table 2, then imports new records into that table. I run the import into table 2 on a semi regular basis but have yet to copy all those records into table 1 successfully.
I need to copy only the records from table 2 to table 1 if the records don't already exist in table1. So, each time the query or vba code would run, it would be continuing to grow table 1 without duplicating existing data.
To clarify further, it's data from the Outlook GAL so each time table2 imports that data (lname,fname,phone,email) it needs to be added to table1, but only if it doesn't already exist in table 1.
I have a small start of SQL but cannot get it to work properly because I'm not sure how to add the other fields into this SQL statement properly (unfortunately I don't know a whole lot about SQL or creating an append query):
INSERT INTO [Current] ( FirstName )
SELECT DISTINCT tblglobaladdresslistimport.First
FROM tblglobaladdresslistimport LEFT JOIN [Current] ON tblglobaladdresslistimport.First = Current.FirstName
WHERE Current.FirstName Is Null;
How about this :
INSERT INTO [Current](FirstName, LastName, Phone, Email)
SELECT DISTINCT
tblglobaladdresslistimport.First
, tblglobaladdresslistimport.Last
, tblglobaladdresslistimport.Phone
, tblglobaladdresslistimport.Email
FROM
tblglobaladdresslistimport LEFT JOIN [Current]
ON tblglobaladdresslistimport.First = Current.FirstName
AND tblglobaladdresslistimport.Last = Current.LastName
AND tblglobaladdresslistimport.Phone = Current.Phone
AND tblglobaladdresslistimport.Email = Current.Email
WHERE Current.FirstName Is Null
AND Current.LastName Is Null
AND Current.Phone Is Null
AND Current.Email Is Null;
Adjust column names if I guessed it wrong. That assumed that you don't have primary key, so data in tblglobaladdresslistimport considered already exists if there is a row in Current having same value for all columns.

Copy data to another table before update or insert. Use stored procedure?

I have two tables that I need to update in a database. I am updating these tables from data in another database. If a record in table 1 gets updated, I need the old information in table 1 to be stored in table 2. I need logic in place to make a comparison and then update Table 2 if needed. My question is, what is the best way to do this? I am thinking a stored procedure would be the way to go, but I'm not sure.
Here is a more visual explanation.
Table 1
Student Grade
james 6
sarah 5
Table 2
EMPTY
Lets say that the data below is what I am pulling from another database.
Other Database
Student Grade
james 6
sarah 4
tom 7
Here is some sloppy logic that may help explain what I need to do.
--If records match do nothing
IF otherDatabase.student = table1.student AND otherDatabase.grade = table1.grade THEN do nothing
--If partial match copy old data to table 2 and insert new data to table1
IF otherDatabase.student = table1.student AND otherDatabse.grade != table1.grade
THEN copy table1.student to table2.student AND copy table1.grade to table2.grade THEN UPDATE table1.grade from otherDatabase.grade
--If no match copy new data to Table1
IF otherDatabase.student != table1.student AND otherDatabase.grade != table1.grade THEN INSERT otherDatabase.student AND otherDatabase.grade INTO table1
In my example, James would not get touched, sarah would get moved to table 2 and then inserted into table 1 with new grade and tom would get inserted into table 1.
I am very sorry if this doesn't make sense. Please allow me to clarify if needed. Thanks
You could do it with a stored procedure, but I would use a trigger.
With a stored procedure, I'd perceive you using a cursor on the otherDatabase table to read through the records and compare each with the values in Table1 to determine whether Table1's data needed to be written to Table2, and if so, to do it.
With a trigger, I would simply update the data in Table1 by whatever means, without concerning myself with what the overwriting data is, and in the trigger,
use the old and new values using the ##Inserted & ##Deleted (system) tables to determine if the old values (##Deleted) needed to be written to Table2. Eg
INSERT Table2 (Student, Grade)
SELECT d.Student, d.Grade
FROM ##Deleted d LEFT JOIN ##Inserted i ON d.[Key] = i.[Key]
WHERE (d.Student <> i.Student OR d.Grade <> i.Grade) AND d.[Key] IS NOT NULL
Drop procedure if exists getCID;
delimiter //
CREATE PROCEDURE getCID(IN cid varchar(100))
BEGIN
create table Temp as(select i.invoice_no,i.cust_id,b.tot_amount,b.paid_amount,b.bal_amount from invoice_item_info i,bill_info b where i.invoice_no=b.invoice_no and i.cust_id=cid);
select * from Temp;
select DISTINCT cust_id,count(invoice_no),sum(tot_amount),sum(paid_amount),sum(bal_amount) from Temp;
Drop table Temp;
END
//
delimiter ;

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.