Cascading data insert - sql-server

I have these 3 tables:
CREATE TABLE tblPrimary(
Id INT IDENTITY(1,1) NOT NULL,
SampleID VARCHAR(8)
PRIMARY KEY (Id)
)
CREATE TABLE tblSecondary(
PrimaryId INT NOT NULL,
SampleName VARCHAR(50) NULL
)
CREATE TABLE tblSample(
SampleId VARCHAR(8) NOT NULL,
Name VARCHAR(50) NULL
PRIMARY KEY (SampleId)
)
Some sample data for tblSample
INSERT INTO tblSample VALUES ('A-1101', 'The CP 1014')
INSERT INTO tblSample VALUES ('A-1102', 'The NT 1014')
INSERT INTO tblSample VALUES ('A-1103', 'The LO 1014')
INSERT INTO tblSample VALUES ('A-1104', 'The AE 1014')
INSERT INTO tblSample VALUES ('A-1105', 'The PW 1014')
INSERT INTO tblSample VALUES ('A-1106', 'The QW 1014')
I'm currently inserting data from tblSample to tblPrimary with the following query:
INSERT INTO tblPrimary
SELECT s.SampleID FROM tblSample s
LEFT JOIN tblPrimary p on s.SampleId = p.SampleID
WHERE s.SampleId NOT IN (SELECT SampleID FROM tblPrimary)
Now I want to insert data into tblSecondary also, during the data insert into tblPrimary.
The newly generated `tblPrimary.PrimaryId` will be inserted into the tblSecondary.PrimiaryId` column
`tblSample.Name` will be inserted into the `tblSecondary.SampleName` column
It will be a cascading data inserting process
What do I need to do after the above insert query for this to get done?
I want the tblSecondary result to be as follows:

You will need a table variable and output clause for this something like....
DECLARE #NewIds (ID INT, SampleID varchar(8));
insert into tblPrimary(SampleID)
OUTPUT inserted.ID, inserted.SampleID INTO #NewIds (ID,SampleID )
select s.SampleID
from tblSample s
left join tblPrimary p on s.SampleId = p.SampleID
where s.SampleId not in (select SampleID from tblPrimary)
-- Now insert rows into tblSecondary table
INSERT INTO tblSecondary(PrimaryId, SampleName )
SELECT n.ID , S.Name
FROM tblSample s
INNER JOIN #NewIds n ON s.SampleId = n.SampleID

Related

How to combine two FOR XML AUTO into 1 XML?

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>

T-SQL insert and update foreign key without cursor

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. :)

SQL Server 2008: Update/Insert data(multiple records) from multiple columns of different tables

I have to write a procedure to update table if record exists, else insert the data. I am getting records from different columns as comma-separated strings.
For example:
ID = "2,3,4,5";
Names = "S,D,G,H";
Approach that I have taken is: Created ID Table and Names Table with single column each. (Split function being used, returns table with single column which contains values). And then I am trying to insert/update the data. Insert is working fine. But for Update record, it's updating with incorrect values.
I am new to SQL and just can't get around with what am I doing wrong or if my approach is fine! Please help. Kindly note, in my approach I have used row_num to pick records in correct order from different temp tables. Following is my code:
Table Design:
CREATE TABLE [dbo].[TestMultipleInsert](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Number] [int] NOT NULL,
[Number1] [int] NULL,
CONSTRAINT [PK_TestMultipleInsert] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Code for Update/Insert
declare #names table (name varchar(50)); --Consider as split string values of Name Column
declare #numbers table (phone int); -- Consider as split string values of Number column
declare #number1s table (phone1 int); -- Consider as split string values of Number1 column
declare #MCodes table (Id int); --Consider as split string values of Id column. If Id = -1, then it's a new entry, else updated record.
-- Insert test data for running query
insert into #names (name) values('First');
insert into #names (name) values('Second');
insert into #names (name) values('Third');
insert into #names (name) values('Fourth');
insert into #numbers (phone) values(112);
insert into #numbers (phone) values(399);
insert into #numbers (phone) values(499);
insert into #numbers (phone) values(499);
insert into #number1s (phone1) values(112);
insert into #number1s (phone1) values(299);
insert into #number1s (phone1) values(399);
insert into #number1s (phone1) values(399);
insert into #MCodes (Id) values(54); --Update
insert into #MCodes (Id) values(-1); --Insert
insert into #MCodes (Id) values(50); --Update
insert into #MCodes (Id) values(-1); --Insert
--Query
insert into dbo.TestMultipleInsert (Name, Number, Number1)
select A.name, B.phone, C.phone1
from(
SELECT name,row_number() over (order by (select 0)) as row_num
FROM #names)A,
(SELECT phone,row_number() over (order by (select 0)) as row_num
FROM #numbers)B,
(SELECT phone1,row_number() over (order by (select 0)) as row_num
FROM #number1s)C,
(SELECT Id,row_number() over (order by (select 0)) as row_num
FROM #MCodes)D
where A.row_num=B.row_num and A.row_num = C.row_num and D.row_num = A.row_num and D.Id = -1
Update dbo.TestMultipleInsert
SET Name=A.Name, Number =B.phone, Number1= C.phone1
from(
SELECT name,row_number() over (order by (select 0)) as row_num
FROM #names)A,
(SELECT phone,row_number() over (order by (select 0)) as row_num
FROM #numbers)B,
(SELECT phone1,row_number() over (order by (select 0)) as row_num
FROM #number1s)C,
(SELECT Id,row_number() over (order by (select 0)) as row_num
FROM #MCodes)D
where D.row_num=B.row_num and D.row_num = C.row_num and D.row_num = A.row_num and D.Id <> -1 and D.Id = dbo.TestMultipleInsert.Id
select * from dbo.TestMultipleInsert;
Any help will be highly appreciated.
A1) I don't know what your big picture is, but your script is working as far as I can tell. The INSERT is inserting what I expect, and the UPDATE is updating the records that I expect. There's nothing technically wrong with using the row_number() over() function, but it's a little more straight-forward with the way I suggest below. (just preference in this situation)
Assuming you must have the four separate tables (temp tables), here is one way to do it. I added auto increment primary keys to the table variables to make joining the data more straight-forward.
You could also use a MERGE statement to do both the update and insert in one go. (About MERGE: https://msdn.microsoft.com/en-us/library/bb510625(v=sql.105).aspx)
--added auto increment primary key to avoid using window function row_nmber() over()...
declare #names table (pkey int primary key identity,name varchar(50)); --Consider as split string values of Name Column
declare #numbers table (pkey int primary key identity, phone int); -- Consider as split string values of Numer column
declare #number1s table (pkey int primary key identity, phone1 int); -- Consider as split string values of Number1 column
declare #MCodes table (pkey int primary key identity,Id int); --Consider as split string values of Id column. If Id = -1, then it's a new entry, else updated record.
-- Insert test data for running query
insert into #names (name) values('First');
insert into #names (name) values('Second');
insert into #names (name) values('Third');
insert into #names (name) values('Fourth');
insert into #numbers (phone) values(112);
insert into #numbers (phone) values(399);
insert into #numbers (phone) values(499);
insert into #numbers (phone) values(499);
insert into #number1s (phone1) values(112);
insert into #number1s (phone1) values(299);
insert into #number1s (phone1) values(399);
insert into #number1s (phone1) values(399);
insert into #MCodes (Id) values(54);
insert into #MCodes (Id) values(-1);
insert into #MCodes (Id) values(50);
insert into #MCodes (Id) values(-1);
--Insert Query
INSERT INTO dbo.TestMultipleInsert (Name, Number, Number1)
SELECT A.name, B.phone, C.phone1
FROM #names A
JOIN #numbers B ON B.pkey = A.pkey
JOIN #number1s C ON C.pkey = A.pkey
JOIN #MCodes D ON D.pkey = A.pkey
WHERE D.Id = -1
--Update query
UPDATE dbo.TestMultipleInsert
SET Name = upd.Name
, Number = upd.phone
, Number1 = upd.phone1
FROM(
SELECT A.name, B.phone, C.phone1, D.Id
FROM #names A
JOIN #numbers B on B.pkey = A.pkey
JOIN #number1s C on C.pkey = A.pkey
JOIN #MCodes D on D.pkey = A.pkey
WHERE D.Id <> -1
) upd
WHERE upd.Id = dbo.TestMultipleInsert.Id
A2) If you need to get a list of the identity values for an insert, declare a table variable (to get rows for all IDs) like this before your script that inserts:
DECLARE #myIDs table (ID int);
Then use the OUTPUT clause with your insert statement (if ID is your key column):
INSERT INTO tableBlah
OUTPUT INSERTED.ID INTO #myIDs
VALUES ...blah blah
You can then join your other queries (update, select etc) to the table variable to find the records that were just inserted.

Get first record from duplicate records and use its identity in other tables

I have two temp tables in which there are duplicates. Two tables contains records as below.
DECLARE #TempCompany TABLE (TempCompanyCode VARCHAR(100), TempCompanyName VARCHAR(100))
INSERT INTO #TempCompany VALUES ('00516','Company1')
INSERT INTO #TempCompany VALUES ('00135','Company1')
INSERT INTO #TempCompany VALUES ('00324','Company2')
INSERT INTO #TempCompany VALUES ('00566','Company2')
SELECT * FROM #TempCompany
DECLARE #TempProduct TABLE (TempProductCode VARCHAR(100), TempProductName VARCHAR(100), TempCompanyCode VARCHAR(100))
INSERT INTO #TempProduct VALUES ('001000279','Product1','00516')
INSERT INTO #TempProduct VALUES ('001000279','Product1','00135')
INSERT INTO #TempProduct VALUES ('001000300','Product2','00135')
INSERT INTO #TempProduct VALUES ('001000278','Product3','00566')
INSERT INTO #TempProduct VALUES ('001000278','Product3','00324')
INSERT INTO #TempProduct VALUES ('001000304','Product4','00566')
SELECT * FROM #TempProduct
Company is master table and product is child table. Product contains reference of company. Now these are my temp tables and I need to insert proper values from these tables to my main table.
I want to insert records as following
DECLARE #Company TABLE(CompanyID INT IDENTITY(1,1), CompanyCode VARCHAR(100), CompanyName VARCHAR(100))
INSERT INTO #Company VALUES ('00516','Company1')
DECLARE #IDOf00516 INT = ##IDENTITY
INSERT INTO #Company VALUES ('00324','Company2')
DECLARE #IDOf00324 INT = ##IDENTITY
SELECT * FROM #Company
DECLARE #Product TABLE(ProductID INT IDENTITY(1,1), ProductCode VARCHAR(100), ProductName VARCHAR(100), CompanyID INT)
INSERT INTO #Product VALUES ('001000279','Product1',#IDOf00516)
INSERT INTO #Product VALUES ('001000300','Product2',#IDOf00516)
INSERT INTO #Product VALUES ('001000278','Product3',#IDOf00324)
INSERT INTO #Product VALUES ('001000300','Product4',#IDOf00324)
SELECT * FROM #Product
I have attached the following image for how it looks when running the queries.
Can anybody help?
I would probably first insert unique records from tempCompany to Company table, then do an insert from TempProduct with a lookup to the inserted Company tables.
I.e. first insert companies:
INSERT INTO #Company (CompanyCode, CompanyName)
SELECT temp.TempCompanyCode, temp.TempCompanyName
FROM #TempCompany AS temp
Then insert products using a join to find the companyid:
INSERT INTO #Product (ProductCode, ProductName, CompanyId)
SELECT temp.TempProductCode, temp.TempProductName, c.CompanyID
FROM #TempProduct AS temp
JOIN #Company AS c ON temp.TempCompanyCode = c.CompanyCode -- Lookup to find CompanyID
However this does not take into account duplicates and the possibility that the main tables already have the records inserted.
Adding duplicate and check for already existing records the end result could look like:
--1. insert records not already in company table:
INSERT INTO #Company (CompanyCode, CompanyName)
SELECT DISTINCT temp.TempCompanyCode, temp.TempCompanyName
FROM #TempCompany AS temp
LEFT JOIN #Company AS c ON temp.TempCompanyCode = c.CompanyCode -- Will match Companies that already exists in #Companies
WHERE c.CompanyID IS NULL -- Company does not already exist
ORDER BY temp.TempCompanyCode
--2. insert product records:
INSERT INTO #Product (ProductCode, ProductName, CompanyId)
SELECT DISTINCT temp.TempProductCode, temp.TempProductName, c.CompanyID
FROM #TempProduct AS temp
JOIN #Company AS c ON temp.TempCompanyCode = c.CompanyCode -- Lookup to find CompanyID
LEFT JOIN #Product AS p ON temp.TempProductCode = p.ProductCode AND temp.TempCompanyCode = c.CompanyCode -- Will match products that already exists in #Products
WHERE p.ProductID IS NULL -- Product does not already exists
ORDER BY c.CompanyID, temp.TempProductCode
--3. Check result
SELECT * FROM #Company
SELECT * FROM #Product
Note that i make use of LEFT JOIN and add a WHERE condition to check whether the record already exists in your main tables.
This could very well be achieved using the MERGE statement - but I'm accustomed to the slighty less readable LEFT JOIN/WHERE method :)
EDIT
Only TempCompanyName is to be used for determining whether a row in TempCompany is unique. I.e. Company1 with CopmpanyCode 00135 should not be inserted.
To achieve this, I would make use of ROW_NUMBER in helping finding the company rows to insert. I've added an identity column to #TempCompany to make sure the first row inserted will be the row used (i.e. to make sure 00516 is used for Company1 and not 00135).
New #TempCompany definition:
DECLARE #TempCompany TABLE (TempCompanyId INT IDENTITY(1,1), TempCompanyCode VARCHAR(100), TempCompanyName VARCHAR(100))
And updated script with row_number added and an extra join from Product via TempCompany (on name) to Company. The extra join is to enable both Product1 with CompanyCode 00516 and CompanyCode 00135 to be handled correctly:
--1. insert records not already in company table:
;WITH OrderedTempCompanyRows AS (SELECT ROW_NUMBER() OVER (PARTITION BY TempCompanyName ORDER BY TempCompanyId) AS RowNo, TempCompanyCode, TempCompanyName FROM #TempCompany)
INSERT INTO #Company (CompanyCode, CompanyName)
SELECT DISTINCT temp.TempCompanyCode, temp.TempCompanyName
FROM OrderedTempCompanyRows temp
LEFT JOIN #Company AS c ON temp.TempCompanyName = c.CompanyName -- Will match Companies that already exists in #Companies
WHERE temp.RowNo = 1 -- Only first company according to row_number
AND c.CompanyID IS NULL -- Company does not already exist
ORDER BY temp.TempCompanyName
--2. insert product records:
INSERT INTO #Product (ProductCode, ProductName, CompanyId)
SELECT DISTINCT temp.TempProductCode, temp.TempProductName, c.CompanyID
FROM #TempProduct AS temp
JOIN #TempCompany tc ON temp.TempCompanyCode = tc.TempCompanyCode -- Find Companyname in #Tempcompany table
JOIN #Company AS c ON tc.TempCompanyName = c.CompanyName -- Join to #Company on Companyname to find CompanyID
LEFT JOIN #Product AS p ON temp.TempProductCode = p.ProductCode AND temp.TempCompanyCode = c.CompanyCode -- Will match products that already exists in #Products
WHERE p.ProductID IS NULL -- Product does not already exists
ORDER BY c.CompanyID, temp.TempProductName
--3. Check result
SELECT * FROM #Company
SELECT * FROM #Product

max of date in a query in sql server

I need help with writing part of query. Here's what I have
create table first_table(empid [varchar] (10) primary key not null,
DateInserted Datetime)
insert into first_table('1001','2012-02-13');
insert into first_table('1002','2013-02-13');
insert into first_table('1003','2014-02-11');
insert into first_table('1004','2012-02-13');
insert into first_table('2001','2012-02-12');
insert into first_table('2002','2014-02-13');
insert into first_table('5001','2014-02-13');
create table second_table(empid [varchar] (10) not null, CompanyID [varchar] (10) not null)
insert into second_table('1001','1');
insert into second_table('1002','1');
insert into second_table('1003','1');
insert into second_table('1004','1');
insert into second_table('2001','2');
insert into second_table('2002','2');
insert into second_table('5001','5');
create table valid_companies(CompanyID [varchar] (10) not null)
insert into valid_companies('1');
insert into valid_companies('2');
I want to select records from first_table that are valid_companies and with max date.
query should print
1003,1,2014-02-11
2002,2,2014-02-13
I am able to get
select DateInserted,ni.empID
,CompanyID
from
[dbo].[second_table] vw
inner join [dbo].[first_table] ni on ni.EmpID=vw.EmpID
where TagValue in(
SELECT DISTINCT [CompanyID]
FROM [dbo].[Valid_Companies]
)
. How to include max(DateInserted) in this query
Thx
R
try this
select e.empid, ec.CompanyID,
Max(e.DateInserted) LatestDate
from second_table ec
join first_table e
on e.empid = ec.empid
join valid_companies v
on v.CompanyID = ec.CompanyID
group by e.empid, ec.CompanyID

Resources