Fill automatic data in second table when insert data in one table - sql

I have two table Table1 and Table2 and structure of table as
Table1
Primary Key | Name
Table2
Primary Key | Table1_Id_pk | Status - true/false value
When I insert data into Table2 I want to automatically transfer that data in table1 from Table2 which have Status false.

You can create AFTER INSERT trigger:
CREATE TRIGGER DataMigration
ON Table2
AFTER INSERT
AS
BEGIN
INSERT INTO Table1
SELECT *
FROM TAble2
WHERe Status = 'false'
END
GO

Check this example, use ##identity to get inserted row-id and use that id for child table.
declare #t1 table (pk int identity(1,1) not null , name varchar(50) )
declare #t2 table (pk int identity(1,1) not null , t1pk int, status bit )
declare #new_table1Id int
insert into #t1 values( 'ajay')
set #new_table1Id = ##IDENTITY -This gives you last inserted id of #t1
insert into #t2 values( #new_table1Id , 0)
select * from #t1
select * from #t2
##IDENTITY official documentation

Related

Compare Column names from 2 diff table in diff db in MS SQL

I am trying to get column names from 2 diff tables in diff db and compare them to see if there is any extra column in any table. They should match exactly. One possible solution could be getting all the column names from both table and dump in a temp table side by side and compare? Pls help.
IF OBJECT_ID('tempdb..#myTable') IS NOT NULL DROP TABLE #myTable
CREATE table #myTable (
table1 varchar(100) null,
table2 varchar(100) null
)
INSERT INTO #myTable (table1)
SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID('table1')
select * from #mytable
DROP TABLE #mytable
I modified your query to this
IF OBJECT_ID('tempdb..#myTable') IS NOT NULL DROP TABLE #myTable
CREATE table #myTable
(
rowNum int IDENTITY(1,1),
table1 varchar(100) null
)
GO
IF OBJECT_ID('tempdb..#myTable2') IS NOT NULL DROP TABLE #myTable2
CREATE table #myTable2
(
rowNum int IDENTITY(1,1),
table2 varchar(100) null
)
GO
USE database1 --your 1st database name here
GO
INSERT INTO #myTable (table1)
(
SELECT
name
FROM sys.columns
WHERE object_id = OBJECT_ID('Table_1'))
GO
USE database2 -- your 2nd database name here
GO
INSERT INTO #myTable2 (table2)
(
SELECT
name
FROM sys.columns
WHERE object_id = OBJECT_ID('Table_2'))
GO
SELECT table1,table2
FROM #myTable m
FULL OUTER JOIN #myTable2 m2 ON m.rowNum = m2.rowNum
ORDER BY table1,table2
DROP TABLE #mytable
DROP TABLE #mytable2

Copy data from one table to another in sql server

Consider the below tables.
Table 1:
ID Name Address DateOfBirth DateOfJoin CurrentProject
Table 2:
ID Name DateOfJoin CurrentProject
How do i write a sql server db script to copy data from Table 2 to Table 1 such that, values of Table 2 should overwrite values of Table 1 while merging except for when Table 2 value is null.
In case, the value of table 2 is null, the value of table 1 will take precedence.
Example in the above tables, the values of DataofJoin and CurrentProject should become values in the table 1 for a specific ID. When DateOfJoin and CurrentProject values are null in table 2, then table 1 value will remain as it is. Also, all the IDs that are present in Table 2 but not in Table 1 should be copied to Table 1 after running the script.
BEGIN
CREATE TABLE #Table1(
ID INT,
Name VARCHAR(50),
Address VARCHAR(50),
DateOfBirth DATE,
DateOfJoin DATE,
CurrentProject VARCHAR(50)
)
CREATE TABLE #Table2(
ID INT,
Name VARCHAR(50),
DateOfBirth DATE,
DateOfJoin DATE,
CurrentProject VARCHAR(50)
);
INSERT INTO #Table1 VALUES
(1,'NAME 1','ADDRESS 1','01/01/1990','01/01/2017','PROJECT 1'),
(2,'NAME 1','ADDRESS 2','01/01/1991','01/01/2017','PROJECT 2'),
(3,'NAME 1','ADDRESS 3','01/01/1992','01/01/2017','PROJECT 3'),
(4,'NAME 1','ADDRESS 4','01/01/1993','01/01/2017','PROJECT 4');
INSERT INTO #Table2 VALUES
(1,'NAME 1','01/01/1990','01/01/1988',NULL),
(3,'NAME 3','01/01/1991',NULL,'PROJECT 33'),
(5,'NAME 5','01/01/1986','01/01/2017','PROJECT 5'),
(6,'NAME 6','01/01/1985','01/01/2017','PROJECT 6');
SELECT * FROM #Table1;
SELECT * FROM #Table2;
-- Insert records which exists in Table but not in table 1
INSERT INTO #Table1(ID,Name,DateOfBirth,DateOfJoin,CurrentProject) SELECT * FROM #Table2 WHERE ID not in (SELECT ID FROM #table1)
-- Update matching id records from table 1 with table 2
UPDATE #Table1 SET
Name = CASE WHEN T2.Name='' or T2.Name IS NULL THEN #Table1.Name ELSE T2.Name END,
DateOfBirth = CASE WHEN T2.DateOfBirth='' or T2.DateOfBirth IS NULL THEN #Table1.DateOfBirth ELSE T2.DateOfBirth END,
DateOfJoin = CASE WHEN T2.DateOfJoin='' or T2.DateOfJoin IS NULL THEN #Table1.DateOfJoin ELSE T2.DateOfJoin END,
CurrentProject = CASE WHEN T2.CurrentProject='' or T2.CurrentProject IS NULL THEN #Table1.CurrentProject ELSE T2.CurrentProject END
FROM #Table2 T2 WHERE #Table1.ID= T2.ID
select * from #Table1
drop table #Table1;
drop table #Table2;
END

Joining multiple table Sql trigger

Hi I am newbie to SQL trigger. since I tried and searched on online and I dont find any clear outcome.
so here is my problem.
I have three tables:
TABLE1 :
ID NAME (columns )
1 prabhu
TABLE2 :
Id COUNTRY (columns )
1 India
I want this to send to log table if anything like insert/update happen in table2
The SQL(DB2) trigger has to do the following and the result should be in log table like this
LOGTABLE:
ID NAME COUNTRY
1 prabhu India
Your help really appreciated.
Try this,
-- Create tables
create table table1(id int, empName varchar(20));
create table table2(id int, country varchar(20));
create table logtable(id int, empName varchar(20), country varchar(20));
-- Create trigger
CREATE TRIGGER logtableAfterInsert ON table2
after INSERT,DELETE,UPDATE
AS
BEGIN
declare #empid int;
declare #empname2 varchar(20);
declare #empcountry varchar(20);
select #empid=i.id from inserted i;
select #empcountry=i.country from inserted i;
select #empname2=tbl1.empName from table1 tbl1 where tbl1.id=#empid;
insert into logtable values(#empid,#empname2,#empcountry);
PRINT 'Inserted'
END
GO
After that insert the values,
insert into table1 values(1, 'prabhu');
insert into table2 values (1, 'India');
Check the results,
select * from table1;
select * from table2;
select * from logtable;
Hope this resolves...
BTW, You need to add the foreign key constraint.
CREATE OR REPLACE TRIGGER logtableAfterUpdate
AFTER UPDATE ON table2
REFERENCING NEW AS NAUDIT OLD AS OAUDIT
FOR EACH ROW MODE DB2SQL
--BEGIN --ATOMIC
insert into logtable
values(
(select id from table2 tbl2 where tbl2.id =OAUDIT.id),
(select empName from table1 tbl1 where tbl1.id=(select id from table2 tbl2 where tbl2.id =OAUDIT.id)),
(select country from table2 tbl2 where tbl2.id =OAUDIT.id)
);
--END;

How to compare column of two table and insert a value into new table based on comparison in stored procedure in SQL Server

I want to create a procedure which should check a column between two tables and insert a value into another table based on comparison.
Table 1:
create table table1
(
ID int not null primary key,
)
Table 2:
Create table table2
(
ItemID int not null primary key,
ID int FOREIGN KEY REFERENCES Orders(OrderID) ,
Descp Text
)
Table 3:
create table table3
(
ID int,
ItemCheck char
)
value of ID column of table 3 should be same as table1's ID column and
if ID column of table1 table exist in table2 then value ItemCheck column of table3 should be 'true' oterwise 'false'.
Please give me some ideas and let me know if you have any doubt. Thanks in advance.
Sounds like you want something like this?
TRUNCATE table3;
INSERT INTO table3 (ID, ItemCheck)
SELECT ID,
CASE WHEN EXISTS (SELECT 1 FROM table2 t2 WHERE ID = t.ID)
THEN 'T'
ELSE 'F'
END
FROM table1 t
Declare #col1 varchar(10)
Declare #col2 varchar(10)
SET #col1 = Select column1 from table1 where id =1
SET #col1 = Select column1 from table1 where id =2
IF(#col1 == #col2)
BEGIN
// insert statement goes here
END

Get Scope identity for multiple inserts

For table1 Inserted 3 records
It should get those three identities and it should insert 3 records in table3 (but it’s not happening- it inserts 3 records with same identity ie.last scope identity)
create table table1(ID INT identity(1,1),Name varchar(50))
insert into table1 values('Ram'),('Sitha'),('Laxman')
create table table1(ID INT identity(1,1),Name varchar(50))
create table table3(ID INT ,Name varchar(50))
insert into table2(Name)
select Name from table1
declare #id int;
set #id= (select scope_Identity())
begin
insert into table3(ID,Name)
select #id,Name from table2
end
select * from table2
select * from table3
How can get all identities to insert do I need to write a loop (or) do I need to Create a trigger.
Please give me a solution I am strugguling from past 4 hours.
Thanks in anvance
Use the OUTPUT clause to handle multi-row inserts:
INSERT INTO dbo.table2(Name)
OUTPUT inserted.ID, inserted.Name INTO table3
SELECT Name FROM dbo.table1;
You can use the OUTPUT clause to get the identity from any number of inserts.
create table table1(ID INT identity(1,1),Name varchar(50))
DECLARE #T1 Table (ID int, name varchar(50))
insert into table1
OUTPUT inserted.ID, Inserted.Name INTO #T1
values('Ram'),('Sitha'),('Laxman')
DECLARE #IdentityId INT,#Count INT=1
DECLARE #temp AS TABLE (Id INT IDENTITY ,Name NVARCHAR(100))
INSERT INTO #temp(Name)
SELECT Name FROM table1
WHILE #Count <=(SELECT COUNT(SId) FROM #temp)
BEGIN
INSERT INTO table2(Name)
SELECT Name FROM #temp
WHERE Id=#Count
SET #IdentityId = SCOPE_IDENTITY()
INSERT INTO tabel3(#IdentityId,Name)
SELECT 3, #IdentityId,1,GETDATE()
SET #Count=#Count+1
END