I have 2 tables "#tblData1" and "#tblData2" link with "Id" column. Table "#tblData2" may or may not data for the same "Id" of "#tblData1".
Create Table #tblData1 (Id int, Details VARCHAR(10), UniqueKey VARCHAR(10), DetectDate DATE, UpdateBy VARCHAR(10));
insert into #tblData1 values (1, 'DT1', 'uq1', '01/15/2016', 'abc'), (2, 'DT2', 'uq2', '01/16/2016', 'xyz');
Create Table #tblData2 (Id int, Details VARCHAR(10), DetectDate DATE);
insert into #tblData2 values (1, 'DT11', '01/16/2016'), (1, 'DT12', '01/17/2016')
Now, I need to insert data into below 3 tables "#tblUniqueKeys", "#tblMaster" and "#tblChild".
Same Identity "MasterId" into both tables "#tblUniqueKeys" and "#tblChild".
Data from "#tblData1" into 2 tables "#tblUniqueKeys" and "#tblMaster".
Data from "#tblData2" into table ""#tblChild".
create Table #tblMaster (MasterId INT IDENTITY(101,1), Details VARCHAR(10), DetectDate DATE, UpdateBy VARCHAR(10));
create Table #tblUniqueKeys (UqId INT IDENTITY(10,1), MasterId INT, UniqueKey VARCHAR(10), DetectDate DATE);
create Table #tblChild (ChildId INT IDENTITY(201,1), MasterId INT, Details VARCHAR(10), DetectDate DATE);
Using below "Merge" sql query, I'm able to insert records into 2 table "#tblUniqueKeys" and "#tblMaster".
Question, How to insert records into the 3rd table "#tblChild"? Can we insert record into 3rd table along with "MasterId" within same Merge query? Thanks!!!
MERGE INTO #tblMaster AS Dest
USING
(
SELECT UniqueKey, Details, DetectDate, UpdateBy
FROM #tblData1
) AS Src
ON (1 = 0)
WHEN NOT MATCHED BY TARGET THEN
INSERT
(
Details
,DetectDate
,UpdateBy)
VALUES
(Src.Details
,Src.DetectDate
,Src.UpdateBy)
OUTPUT inserted.MasterId, Src.UniqueKey, Src.DetectDate
INTO #tblUniqueKeys(MasterId, UniqueKey, DetectDate);
select * from #tblMaster
select * from #tblUniqueKeys
DROP TABLE #tblData1;
drop table #tblData2;
DROP TABLE #tblMaster;
drop table #tblChild
DROP TABLE #tblUniqueKeys;
Related
We are using SQL Server 2012.
Table myTbl has a one to many relationship to table myAllocation
Table ABC_myTbl has a one to many relationship to table ABC_myAllocation
The below query combined 2 FOR XML AUTO into 1 XML, but the problem is ID, SystemSource, Manager are included in element TradeTicket instead of on their own, and accountManager, unitPrice are included in element allocationRow instead of on their own.
Thank you
SELECT '<?xml version="1.0"?>'+
(SELECT
( SELECT trTicket.[id],trTicket.[manager],'PFM' as SystemSource
,allocationRow.accountNumber,allocationRow.unitPrice
FROM myTbl AS trTicket
LEFT JOIN myAllocation AS allocationRow ON allocationRow.trade_ticket_id=trTicket.id
WHERE trTicket.ID = 8779631
ORDER BY trTicket.id,allocationRow.AccountNumber
FOR XML AUTO, type)
,
(
SELECT trTicket.[id],trTicket.[manager],'CRD' as SystemSource
,allocationRow.accountNumber,allocationRow.unitPrice
FROM ABC_myTbl AS trTicket
LEFT JOIN ABC_myAllocation AS allocationRow ON allocationRow.trade_ticket_id=trTicket.id
WHERE trTicket.ID = 8
ORDER BY trTicket.id,allocationRow.AccountNumber
FOR XML AUTO, type)
FOR XML PATH('trTickets'), ELEMENTS) AS XMLResult
This is the current result:
<?xml version="1.0"?>
<trTickets>
<trTicket id="8779631" SystemSource="PFM" manager="MCM">
<allocationRow accountNumber="292 " unit_Price="300"/>
</trTicket>
<trTicket id="8" SystemSource="CRD" manager="DOYLE">
<allocationRow unitPrice="100" accountNumber="F11 "/>
<allocationRow unitPrice="200" accountNumber="F22 "/>
</trTicket>
</trTickets>
This is the desired result that I am looking for:
<?xml version="1.0"?>
<trTickets>
<trTicket>
<id>8</id>
<manager>DOYLE</manager>
<SystemSource>CRD</SystemSource>
<allocationRow>
<accountNumber>F11</accountNumber>
<unitPrice>100</unitPrice>
</allocationRow>
<allocationRow>
<accountNumber>F22</accountNumber>
<unitPrice>200</unitPrice>
</allocationRow>
</trTicket>
<trTicket>
<id>8779631</id>
<manager>MCM</manager>
<SystemSource>PFM</SystemSource>
<allocationRow>
<accountNumber>292</accountNumber>
<unitPrice>300</unitPrice>
</allocationRow>
</trTicket>
</trTickets>
Data sample:
Table ABC_myTbl:
ID Manager
-----------
8 DOYLE
Table ABC_myAllocation:
accountNumber unitPrice
-------------------------
F11 100
F22 200
Table myTbl:
ID Manager
---------------
8779631 MCM
Table myAllocation:
accountNumber unitPrice
--------------------------
292 300
DDL for the tables and their data:
CREATE TABLE dbo.ABC_myTbl
(
ID INT NOT NULL,
MANAGER VARCHAR(10) NOT NULL
)
CREATE TABLE dbo.myTbl
(
ID INT NOT NULL,
MANAGER VARCHAR(10) NOT NULL
)
CREATE TABLE dbo.ABC_myAllocation
(
accountNumber VARCHAR(10) NOT NULL,
unitprice NUMERIC(10, 3) NOT NULL
)
CREATE TABLE dbo.myAllocation
(
accountNumber VARCHAR(10) NOT NULL,
unitprice NUMERIC(10, 3) NOT NULL
)
INSERT INTO dbo.ABC_myTbl VALUES (8,'DOYLE')
INSERT INTO dbo.ABC_myAllocation VALUES ('F11',100)
INSERT INTO dbo.ABC_myAllocation VALUES ('F22',200)
INSERT INTO dbo.myTbl VALUES (8779631,'MCM')
INSERT INTO dbo.myAllocation VALUES ('292',300)
I didn't wait for your DDL and sample data population. So I created a conceptual sample for you. Please pay attention that the tables have implied relationships and they are used in the WHERE clauses.
SQL
-- DDL and sample data population, start
DECLARE #tbl1 TABLE (ID INT PRIMARY KEY, Manager VARCHAR(20));
INSERT INTO #tbl1 (ID, Manager) VALUES
(8, 'DOYLE'),
(9, 'XYZ');
DECLARE #tbl1Child TABLE (accountNumber CHAR(3) PRIMARY KEY, ParentID INT, unitPrice DECIMAL(10,2));
INSERT INTO #tbl1Child (accountNumber, ParentID, unitPrice) VALUES
('F11', 8, 100)
,('F22', 8, 200)
,('F70', 9, 770);
DECLARE #tbl2 TABLE (ID INT PRIMARY KEY, Manager VARCHAR(20));
INSERT INTO #tbl2 (ID, Manager) VALUES
(8779631, 'MCM')
,(8779555, 'TTT');
DECLARE #tbl2Child TABLE (accountNumber CHAR(3) PRIMARY KEY, ParentID INT, unitPrice DECIMAL(10,2));
INSERT INTO #tbl2Child (accountNumber, ParentID, unitPrice) VALUES
('292', 8779631, 300)
,('255', 8779555, 500);
-- DDL and sample data population, end
SELECT TOP(1) NULL
, (
SELECT *
, (
SELECT * FROM #tbl1Child AS c
WHERE p.ID = c.ParentID
FOR XML PATH('allocation_row'), TYPE
)
FROM #tbl1 AS p
FOR XML PATH('tradeTicket'), TYPE
)
, (
SELECT *
, (
SELECT * FROM #tbl2Child AS c
WHERE p.ID = c.ParentID
FOR XML PATH('allocation_row'), TYPE
)
FROM #tbl2 AS p
FOR XML PATH('tradeTicket'), TYPE
)
FROM #tbl1
FOR XML PATH(''), TYPE, ROOT('tradeTickets');
Output
<tradeTickets>
<tradeTicket>
<ID>8</ID>
<Manager>DOYLE</Manager>
<allocation_row>
<accountNumber>F11</accountNumber>
<ParentID>8</ParentID>
<unitPrice>100.00</unitPrice>
</allocation_row>
<allocation_row>
<accountNumber>F22</accountNumber>
<ParentID>8</ParentID>
<unitPrice>200.00</unitPrice>
</allocation_row>
</tradeTicket>
<tradeTicket>
<ID>9</ID>
<Manager>XYZ</Manager>
<allocation_row>
<accountNumber>F70</accountNumber>
<ParentID>9</ParentID>
<unitPrice>770.00</unitPrice>
</allocation_row>
</tradeTicket>
<tradeTicket>
<ID>8779555</ID>
<Manager>TTT</Manager>
<allocation_row>
<accountNumber>255</accountNumber>
<ParentID>8779555</ParentID>
<unitPrice>500.00</unitPrice>
</allocation_row>
</tradeTicket>
<tradeTicket>
<ID>8779631</ID>
<Manager>MCM</Manager>
<allocation_row>
<accountNumber>292</accountNumber>
<ParentID>8779631</ParentID>
<unitPrice>300.00</unitPrice>
</allocation_row>
</tradeTicket>
</tradeTickets>
Below are my tables and I want to calculation as per formula and insert in table3 with employees.
I have 3 tables
table1 payhead master
table2 employee payheadwise salary
table3 (the destination table)
I want to calculate as per formula column and insert into table3
For example in table 2 employeid-E001 in Pay1-2000 so for Pay2 which is formula column should calculate as per pay1 value and insert into table 3 like empid-E001,payid-pay1,amount-2000 next,Empid-E001,Payid-pay2,amount-240(calculate as 2000*12/100) NextRow-Empid-E001,Payid-pay3,Amount-2240(pay1+pay2) .so as per formula it should be calculate and insert into 3rd table.
please, somebody, help me.
CREATE TABLE #Table1
(
ID VARCHAR(5),
formula VARCHAR(MAX)
)
CREATE TABLE #table2
(
employeid VARCHAR(5),
payhead VARCHAR(5),
amount MONEY
)
CREATE TABLE #table3
(
employeid VARCHAR(5),
payiD VARCHAR(5),
amount MONEY
)
INSERT INTO #Table1
VALUES ('PAY1', NULL), ('PAY2', '(PAY1+PAY2*12%)'), ('PAY3', 'PAY1 + PAY2')
INSERT INTO #Table2
VALUES ('E001', 'PAY1', 2000), ('E002', 'PAY1', 5000), ('E003', 'PAY1', 3000)
INSERT INTO #Table2
VALUES ('E001', 'PAY3', 1000), ('E002', 'PAY3', 3000), ('E003', 'PAY3', 2000)
I have two tables in MS SQL:
CREATE TABLE Table1 (ID INT IDENTITY(1,1) NOT NULL, TEXTVal VARCHAR(100), Table2Id int)
insert into Table1 (TEXTVal) values('aaa');
insert into Table1 (TEXTVal) values('bbb'); insert into Table1 (TEXTVal) values('ccc');
CREATE TABLE Table2 (ID INT IDENTITY(1,1) NOT NULL, TEXTVal VARCHAR(100), Table2Id int)
Id are identity columns. I want to copy TEXTVal values from Table1 to Table2:
INSERT INTO Table2 (TEXTVal)
SELECT TEXTVal FROM Table1
where TEXTVal <> 'ccc'
and after that update column Table2Id in Table1 with appropriate values of Id from Table2. I can do this with cursor and SCOPE_IDENTITY().
I am just wondering, is there a way to do it without cursor in T-SQL?
As Jeroen stated in comments, you'll want to use OUTPUT. In the following example if you don't have an AdventureWorks database, just use a test database. You should be able to copy/paste this and just run it to see it in action!
USE AdventureWorks;
GO
----Creating the table which will store permanent table
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
----Creating temp table to store ovalues of OUTPUT clause
DECLARE #TmpTable TABLE (ID_New INT, TEXTVal_New VARCHAR(100),ID_Old INT, TEXTVal_Old VARCHAR(100))
----Insert values in real table
INSERT TestTable (ID, TEXTVal)
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
VALUES (2,'SecondVal')
----Update the table and insert values in temp table using Output clause
UPDATE TestTable
SET TEXTVal = 'NewValue'
OUTPUT Inserted.ID, Inserted.TEXTVal, Deleted.ID, Deleted.TEXTVal INTO #TmpTable
WHERE ID IN (1,2)
----Check the values in the temp table and real table
----The values in both the tables will be same
SELECT * FROM #TmpTable
SELECT * FROM TestTable
----Clean up time
DROP TABLE TestTable
GO
ResultSet:
TmpTable:
ID_New TextVal_New ID_Old TextVal_Old
——————— ——————— ——————— ———————
1 NewValue 1 FirstVal
2 NewValue 2 SecondVal
Original Table:
ID TextVal
——————— ———————
1 NewValue
2 NewValue
As you can see it is possible to capture new values, and the values you are updating. In this example I'm just stuffing them into a table variable but you could do whatever you'd like with them. :)
I have the 5 employee tables as shown below.
---Table: Emp_1
CREATE TABLE Emp_1
(
Emp_ID VARCHAR(10),
Emp_FName VARCHAR(10),
Emp_LName VARCHAR(10),
Emp_PNumber VARCHAR(10)
);
---Table: Emp_2
CREATE TABLE Emp_2
(
Emp_ID VARCHAR(10),
Emp_FName VARCHAR(10),
Emp_LName VARCHAR(10),
Emp_PNumber VARCHAR(10)
);
---Table: Emp_3
CREATE TABLE Emp_3
(
Emp_ID VARCHAR(10),
Emp_FName VARCHAR(10),
Emp_LName VARCHAR(10),
Emp_PNumber VARCHAR(10)
);
---Table: Emp_4
CREATE TABLE Emp_4
(
Emp_ID VARCHAR(10),
Emp_FName VARCHAR(10),
Emp_LName VARCHAR(10),
Emp_PNumber VARCHAR(10)
);
---Table: Emp_5
CREATE TABLE Emp_5
(
Emp_ID VARCHAR(10),
Emp_FName VARCHAR(10),
Emp_LName VARCHAR(10),
Emp_PNumber VARCHAR(10)
);
--Insertion: Emp_1
INSERT INTO Emp_1 VALUES('A1','Abram','Mak','123');
INSERT INTO Emp_1 VALUES('A2','Sam','William','321');
--Insertion: Emp_2
INSERT INTO Emp_2 VALUES('A3','John','Marsh','456');
INSERT INTO Emp_2 VALUES('A4','Tom','Lee','654');
--Insertion: Emp_3
INSERT INTO Emp_3 VALUES('A5','Abram','Mak','789');
INSERT INTO Emp_3 VALUES('A6','Shawn','Meben','987');
--Insertion: Emp_4
INSERT INTO Emp_4 VALUES('A7','Sam','William','189');
INSERT INTO Emp_4 VALUES('A8','Mark','Boucher','287');
--Insertion: Emp_5
INSERT INTO Emp_5 VALUES('A9','Gery','Joy','907');
INSERT INTO Emp_5 VALUES('A10','Anthony','Desosa','977');
Now I will insert the each table name into Container table.
I have the following table called as Container which contains the table names, which may be many in my
case I have just inserted 5 as shown below.
--Table : Container
CREATE TABLE Container
(
TableName VARCHAR(50)
);
--Insertion
INSERT INTO Container VALUES('Emp_1');
INSERT INTO Container VALUES('Emp_2');
INSERT INTO Container VALUES('Emp_3');
INSERT INTO Container VALUES('Emp_4');
INSERT INTO Container VALUES('Emp_5');
Note: Now I want to delete the duplicate row from each table and want to keep the original as it is.
And the condition for delete the duplicate row is:
If the Emp_FName and Emp_LName is match with the other tables then the duplicated row has to be deleted and
original row keep as it is.
In my example the Emp_FName and Emp_LName : 'Abram','Mak' repeated in the table Emp_3 which has to be deleted and original
one which is present in the table Emp_1 has keep as it is.
And Emp_FName and Emp_LName : 'Sam','William' repeated in the table Emp_4 which has to be deleted and original
one which is present in the table Emp_1 has keep as it is.
For single Table: For single table I can use the following script to delete the duplicate one and keep the original one.
;WITH CTE AS
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY Emp_FName,Emp_LName ORDER BY Emp_FName) Row_Number FROM Emp_1
)
DELETE FROM CTE
WHERE Row_Number > 1;
My question is how to delete duplicate row from the multiple tables which are dynamic I mean in my Container table the tables
may be more than 5 also.
This query will delete it (emp1 > emp2 ... > emp5):
Declare #sql nvarchar(max) = ''
Select #sql = coalesce(#sql, '')+ '
Delete d From ['+c2.TableName+'] as d
Inner join ['+c1.TableName+'] as c on c.Emp_FName = d.Emp_FName and c.Emp_LName = d.Emp_LName;
'
From Container as c1
Inner Join Container as c2 On c2.TableName > c1.TableName
Order By c1.TableName, c2.TableName
Print #sql
EXEC sp_executesql #sql
However, I think you should take some time to think about your system and data model and try to find a better way of doing it without using dynamic queries.
I have two tables with foreign key constraint on TableB on TablesAs KeyA column. I was doing manual inserts till now as they were only few rows to be added. Now i need to do a bulk insert, so my question if i insert multiple rows in TableA how can i get all those identity values and insert them into TableB along with other column values. Please see the script below.
INSERT INTO Tablea
([KeyA]
,[Value] )
SELECT 4 ,'StateA'
UNION ALL
SELECT 5 ,'StateB'
UNION ALL
SELECT 6 ,'StateC'
INSERT INTO Tableb
([KeyB]
,[fKeyA] //Get value from the inserted row from TableA
,[Desc])
SELECT 1 ,4,'Value1'
UNION ALL
SELECT 2 ,5,'Value2'
UNION ALL
SELECT 3 ,6, 'Value3'
You can use the OUTPUT clause of INSERT to do this. Here is an example:
CREATE TABLE #temp (id [int] IDENTITY (1, 1) PRIMARY KEY CLUSTERED, Val int)
CREATE TABLE #new (id [int], val int)
INSERT INTO #temp (val) OUTPUT inserted.id, inserted.val INTO #new VALUES (5), (6), (7)
SELECT id, val FROM #new
DROP TABLE #new
DROP TABLE #temp
The result set returned includes the inserted IDENTITY values.
Scope identity sometimes returns incorrect value. See the use of OUTPUT in the workarounds section.