Insert into table select from table a and table b where - sql

I want to insert data into a table by joining two tables with a where condition that each id matches.
INSERT INTO SALES(T_ID, SF)
SELECT B.T_ID, B.SF
FROM HIS B, SALES C
WHERE C.REP_ID=B.REP_ID;
I am getting an error that I cannot insert NULL into ("c.REP_ID")
I am not trying to insert anything into c.rep_id. I want to insert values into t_id, sf from HIS table where the rep_id on his table = rep id on sales table.

INSERT INTO SALES (T_ID, SF)
SELECT h.T_ID, h.SF FROM HIS h, SALES C
WHERE C.REP_ID=B.REP_ID;
Note: Make sure that the data comes from select tables is equally compare and valid with the datatypes of the columns where you inserting.

The error simply means that the column REP_ID in the SALES table has a NOT NULL constraint. Your INSERT statement doesn't insert any value into that column (you only insert T_ID and SF) and presumably there are no before-row triggers that will set that column for you.

Related

Insert only new records that are added to TABLE A into TABLE B

Presently I have 2 tables in a SQL database: Table A and Table B
I am using the syntax
Insert Into TABLE B
Select id, col, col, col......
From TABLE A
Where id NOT IN (SELECT id from TABLE B)
End;
This syntax works great. However, if I delete a record that is in TABLE B, the above code would in return, insert the deleted record back into TABLE B. I do not want this to happen. Is there another way to insert a record that is NOT IN TABLE B "only once". It should basically ignore all other previously inserted records which were inserted into TABLE B. If it was deleted it should not be inserted a second time.
I want it to only insert only new records added to TABLE A.
If the ID is consecutive integer then you can use:
Insert Into TABLE B
Select id, col, col, col......
From TABLE A
where ID > select(max(id) from table B)

Creating a trigger that replaces null values in an insert with values already present in the table in SQL Server

I have a table, known as Fruit_Veg_Product_Table which is used to contain the characteristics of certain fruit and vegetable stock.
The table has the following columns:
Product_ID
Product_Type
Product_Name
Product_Colour
Product_Price
Product_In_Sale
Product_Stock_Level
Product_Height
Product_Width
Product_Depth
Product_Package_Height
Product_Package_Width
Product_Package_Depth
When a new product is inserted into the table, sometimes the product is inserted without any dimensions (the columns from Product_Height all the way to Product_Package_Depth). In this circumstance, the dimensions are entered as NULL.
I am in need of a SQL Server trigger that will replace all the NULL values from the attempted insert with the values corresponding to products that are already stored in the table which share a common Product_Type with the product that is being entered.
Any help with this problem is greatly appreciated.
Triggers have an INSERTED logical table that can be used to join the inserted row data back to the physical table. Here is an example:
CREATE TRIGGER Fruit_Veg_Product_Table_Trg
ON dbo.Fruit_Veg_Product_Table
FOR INSERT
AS
UPDATE dbo.Fruit_Veg_Product_Table
SET Product_Package_Height = ca.Product_Package_Height,
Product_Package_Width = ca.Product_Package_Width,
Product_Package_Depth = ca.Product_Package_Depth
FROM dbo.Fruit_Veg_Product_Table
CROSS APPLY
(
SELECT TOP 1
Product_Package_Height,
Product_Package_Width,
Product_Package_Depth
FROM dbo.Fruit_Veg_Product_Table AS fvpt
WHERE dbo.Fruit_Veg_Product_Table.Product_Type = fvpt.Product_Type
AND Product_Package_Height IS NOT NULL
AND Product_Package_Width IS NOT NULL
AND Product_Package_Depth IS NOT NULL
) AS ca
WHERE EXISTS
(
SELECT *
FROM INSERTED
WHERE INSERTED.Product_ID = dbo.Fruit_Veg_Product_Table.Product_ID
AND INSERTED.Product_Package_Height IS NULL
AND INSERTED.Product_Package_Width IS NULL
AND INSERTED.Product_Package_Depth IS NULL
);
GO

How do I insert data from one table to another when there is unequal number of rows in one another?

I have a table named People that has 19370 rows with playerID being the primary column. There is another table named Batting, which has playerID as a foreign key and has 104324 rows.
I was told to add a new column in the People table called Total_HR, which is included in the Batting table. So, I have to insert that column data from the Batting table into the People table.
However, I get the error:
Msg 515, Level 16, State 2, Line 183 Cannot insert the value NULL into
column 'playerID', table 'Spring_2019_BaseBall.dbo.People'; column
does not allow nulls. INSERT fails. The statement has been terminated.
I have tried UPDATE and INSERT INTO SELECT, however got the same error
insert into People (Total_HR)
select sum(HR) from Batting group by playerID
I expect the output to populate the column Total_HR in the People table using the HR column from the Batting table.
You could use a join
BEGIN TRAN
Update People
Set Total_HR = B.HR_SUM
from PEOPLE A
left outer join
(Select playerID, sum(HR) HR_SUM
from Batting
group by playerID) B on A.playerID = B.playerID
Select * from People
ROLLBACK
Notice that I've put this code in a transaction block so you can test the changes before you commit
From the error message, it seems that playerID is a required field in table People.
You need to specify all required fields of table People in the INSERT INTO clause and provide corresponding values in the SELECT clause.
I added field playerID below, but you might need to add additional required fields as well.
insert into People (playerID, Total_HR)
select playerID, sum(HR) from Batting group by playerID
It is strange, however, that you want to insert rows in a table that should already be there. Otherwise, you could not have a valid foreign key on field playerID in table Batting... If you try to insert such rows from table Batting into table People, you might get another error (violation of PRIMARY KEY constraint)... Unless... you are creating the database just now and you want to populate empty table People from filled/imported table Batting before adding the actual foreign key constraint to table People. Sorry, I will not question your intentions. I personally would consider to update the query somewhat so that it will not attempt to insert any rows that already exist in table People:
insert into People (playerID, Total_HR)
select Batting.playerID, sum(Batting.HR)
from Batting
left join People on People.playerID = Batting.playerID
where People.playerID is null and Batting.playerID is not null
group by playerID
You need to calculate the SUM and then join this result to the People table to bring into the same rows both Total_HR column from People and the corresponding SUM calculated from Batting.
Here is one way to write it. I used CTE to make is more readable.
WITH
CTE_Sum
AS
(
SELECT
Batting.playerID
,SUM(Batting.HR) AS TotalHR_Src
FROM
Batting
GROUP BY
Batting.playerID
)
,CTE_Update
AS
(
SELECT
People.playerID
,People.Total_HR
,CTE_Sum.TotalHR_Src
FROM
CTE_Sum
INNER JOIN People ON People.playerID = CTE_Sum.playerID
)
UPDATE CTE_Update
SET
Total_HR = TotalHR_Src
;

Complex insert statements

I want to ask is it possible to insert your own value in the table as well as select other values in other table? I have tried to come out with my select and insert statement but i'm missing one statement as i want to insert my own values in rather than referencing it.
All my required tables have been created. And I wish to insert my own values like Type and rest of the insert values will be selected from other tables.
Below is my code: (Am i missing a statement?)
Insert Into Test (Test_Date, Testno, Examno, Serialno, Type, Hours)
Select S.Test_Date, E.Testno, S.Examno, S.Serialno, Type, (F.STARTED- F.ENDED) as hours
From Semester S, TIME F, TESTPAPERS e
Where S.Testno = F.Testno
And E.Testno = 1
and TYPE = 'Non-FLight'; -- this is the statement that i wish to insert own values instead and not selecting.
Is it possible to do all in one insert statement ? I don't wish to update my table so many times just to insert type value.
Thanks
Just put the value you would like for Type in your select statement:
Insert Into Test (Test_Date, Testno, Examno, Serialno, Type, Hours)
Select S.Test_Date, E.Testno, S.Examno, S.Serialno, 'Non-Flight', (F.STARTED- F.ENDED) as Hours
From Semester S, TIME F, TESTPAPERS e
Where S.Testno = F.Testno And E.Testno = 1

insert one column data from a table into other table, but the other column data will be specified dynamically

i have 2 tables.
TABLE A COLUMNS - aid , aname
TABLE B COLUMNS - bid , bname
from table A, i will pick up data from column 'aid',
AND insert it in 'bid' column of table B , but in bname column of table B, i will insert a new value. how do i do this?
create table A(aid int,aname char)
insert into A values(111, 'e')
create table B(bid int, bname char)
insert into B (bid,bname)
bid will take value from the query : select aid from a
bname will get a new value -m
expected result should be : THE TABLE B WILL HAVE :
bid bname
--- -----
111 m
Try this:
insert into b (bid, bname) select aid, 'm' as bname_fixed_val from a
Two facts enabled the solution above:
The insert .. select clause allows you to insert the values returned with any select.
You can return constant values as fields with select, like for instance:
SELECT 0 as id, 'John' as name
Combining these two points together, I used an insert..select clause to select the field value from the first table (aid), along with a constant value for the second field (m). The AS bname_fixed_val clause is simply a field alias, and can be omitted.
For more information on SQL, here 's a link: http://www8.silversand.net/techdoc/teachsql/index.htm, although googling it wouldn't hurt also.