Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am passing datatable as input parameter to stored procedure.Datatable contain id, Name,Lname,Mobileno,EmpId. Employee tbl contain [Name],[Lname],[mobno],[Did] as columns. When user login that user's Id come as DId.There are more than 1000 records.Instead of passing that id to datatable.I have created separete parameter to sp.'I want add record into Employee which are not already exist.If combination of mobileno and Did is already exist don't insert into Emp else insert.'Datatable contain now of record which may be duplicate.So I don't want to include that record.I want select only distinct record and only that want to add.'I am interested in mobile no.If there are 10 records having same moble no,I am fetching record which come first. Following code is right or wrong.According to my knowledge,first from clause then inner join then where then select execute.Record get fetched from datatable then inner join happens generate result,from that result not from datatable it will check record. So it will give me proper output.

SQL
Create Procedure Proc_InsertEmpDetails
  @tblEmp EmpType READONLY,
  @DId int
  as
begin
INSERT INTO Employee
            ([Name],[Lname],[mobno],[Did])
SELECT [Name],[Lname],[mobno] @DId
FROM   @tblEmp A
Inner join (
             select min(Id) as minID, mobno from @tblEmp group by mobno
           ) MinIDTbl
          on MinIDTbl.minID =  A.ExcelId
WHERE  NOT EXISTS (SELECT 1
                   FROM   Employee B
                   WHERE  B.[mobno] = A.[mobno]
                   AND B.[Did] =  @DId )
end
or does I need to change like this


SQL
INSERT INTO Employee
            ([Name],[Lname],[mobno],[Did])
SELECT C.[Name],C.[Lname],C.[mobno], C.D_Id
from
(SELECT [Name],[Lname],[mobno] @DId as D_Id
FROM   @tblEmp A
Inner join (
                   select min(Id) as minID, mobno from @tblEmp group by mobno
                   ) MinIDTbl
       on MinIDTbl.minID =  A.ExcelId
)C
WHERE  NOT EXISTS (SELECT 1
                   FROM   Employee B
                   WHERE  B.[mobno] = C.[mobno]
                          AND B.[Did] =  @DId )
Posted
Updated 21-Apr-15 22:34pm
v2
Comments
Tomas Takac 22-Apr-15 5:25am    
I think both queries will give the same results. Do you have any particular problem?
Member 11589429 22-Apr-15 7:52am    
No I don't have any problem.If I used first one,still it work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900