Create Table Employees
(
Employee varchar(10),
Manager varchar(10)
);
Insert into Employees
values
('Charlie',null),
('Peter','James'),
('Elai',null),
('Graham','Emanuel'),
('Amanda','Charlie'),
('Sen','Graham'),
('Emanuel',null),
('James','Amanda'),
('Elai',null),
('Victor','Elai');
Above "Employees" table contains employee and employee's manager name. When trying to retrieve comma separated hierarchy of a employee using below function, the result is always null.
for example :
employee 'Victor', hierarchy/result should be "Victor, Elai".
Could anyone point out what am I doing wrong in below UDF.
Create Function EmployeeHierarchy(#employeeName varchar(20))
Returns varchar(100)
AS
Begin
Declare #commaSeparatedHierarchy varchar(100);
Declare #manager varchar(20);
if(#employeeName is not null)
Begin
Select #manager=Manager from Employees where Employee=#employeeName;
Set #commaSeparatedHierarchy=dbo.EmployeeHierarchy(#manager)+','+#manager;
End
return #commaSeparatedHierarchy;
End;
First & foremost, you DO NOT want to create this as a scalar function. Their performance is horrible any udf you create, should be created as an inline table valued function. The following should do what you're looking for...
-- the test data...
USE tempdb;
GO
IF OBJECT_ID('tempdb.dbo.Employee', 'U') IS NOT NULL
DROP TABLE dbo.Employee;
CREATE TABLE dbo.Employee (
Employee varchar(10),
Manager varchar(10)
);
INSERT dbo.Employee (Employee, Manager) VALUES
('Charlie',null),
('Peter','James'),
('Elai',null),
('Graham','Emanuel'),
('Amanda','Charlie'),
('Sen','Graham'),
('Emanuel',null),
('James','Amanda'),
('Elai',null),
('Victor','Elai');
SELECT * FROM dbo.Employee e;
iTVF code...
CREATE FUNCTION dbo.EmployeeHierarchy
(
#employeeName varchar(20)
)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
WITH
cte_Recur AS (
SELECT
CSH = CAST(CONCAT(e.Employee, ', ' + e.Manager) AS VARCHAR(1000)),
e.Manager,
NodeLevel = 1
FROM
dbo.Employee e
WHERE
e.Employee = #employeeName
UNION ALL
SELECT
CSH = CAST(CONCAT(r.CSH, ', ' + e.Manager) AS VARCHAR(1000)),
e.Manager,
NodeLevel = r.NodeLevel + 1
FROM
dbo.Employee e
JOIN cte_Recur r
ON e.Employee = r.Manager
WHERE
e.Manager IS NOT NULL
)
SELECT
commaSeparatedHierarchy = MAX(r.CSH)
FROM
cte_Recur r;
GO
Sample execution...
SELECT
eh.commaSeparatedHierarchy
FROM
dbo.EmployeeHierarchy('peter') eh;
... and the results...
commaSeparatedHierarchy
------------------------------
Peter, James, Amanda, Charlie
Related
Table Employee:
ID, Designation, PromotionDate
Code:
ALTER FUNCTION GetTheDesignationEmployee
(#EmpID INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #Designation VARCHAR(25) = ''
SELECT #Designation = Designation
FROM Employee
WHERE PromotionDate = (SELECT MAX(PromotionDate)
FROM Employee
WHERE ID = #EmpID)
RETURN(#Designation)
END
If I run the code, I should get the current designation of the employee. I pass the ID, and should get back the corresponding current designation.
SELECT dbo.GetTheDesignationEmployee(5346)
But I get an error instead of an answer.
Most likely; if I interpret your last comment correctly, you're getting a designation with a proper date - but since you've forgot to limit the outer SELECT to use the #EmpID passed it, it might be someone else's (with the same PromotionDate)....
Try this:
ALTER FUNCTION GetTheDesignationEmployee
(#EmpID INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #Designation VARCHAR(25) = ''
SELECT #Designation = Designation
FROM EmployeeDetails
WHERE PromotionDate = (SELECT MAX(PromotionDate)
FROM EmployeeDetails
WHERE ID = #EmpID)
-- you need to also include the #EmpID here!
AND ID = #EmpID;
RETURN(#Designation)
END
Or you could write the whole function much simpler:
ALTER FUNCTION GetTheDesignationEmployee
(#EmpID INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #Designation VARCHAR(25) = ''
SELECT TOP (1) #Designation = Designation
FROM EmployeeDetails
WHERE ID = #EmpID
ORDER BY PromotionDate DESC;
RETURN(#Designation)
END
WORD of warning: scalar functions that are doing data access are notoriously bad for performance - so maybe you want to think about another way to get that "most recent designation" in your query to avoid having to write and use this function in the first place.
Sir, below is my SQL query, followed with two images of Query Result & Required Output.
As you can see on Result image that I have got this output from executing the following query.
There is second image of Required Output. I would need to display the output in that format. As First Department name should be at top & below Project details correspond to that department. The same cycle should get repeated for each and every department.
How should I achieve this ?
SQL Code:
DECLARE #ColName varchar(20)=null,
#Query varchar(MAX)=null,
#DepartmentName varchar(50)=null,
#deptt_code varchar(4)=null,
#DistrictId varchar(4)='0001',
#Deptt_Id char(4)=null,
#stYear varchar(4)=null,
#cYear varchar(4)=null,
#yr varchar(9)='2017-2018',
#tno int
BEGIN
set #stYear = SUBSTRING(#yr,0,5);
set #cYear = SUBSTRING(#yr,6,4);
--CREATE DYNAMIC TABLE WITH COLs
DECLARE #DepartmentTable table
(
department_name varchar(50),
department_code varchar(4)
);
DECLARE #ProjectTable table
(
project_name varchar(130),
project_code varchar(15),
department_code varchar(4),
department_name varchar(50),
district_code varchar(4),
district_name varchar(30),
tehsil_code varchar(6),
tehsil_name varchar(30),
service_code varchar(3),
[service_name] varchar(30),
sector_code varchar(3),
sector_name varchar(30),
project_start_year varchar(8),
project_compl_year varchar(8),
financial_year varchar(9)
);
--Insert into Department Table
INSERT INTO #DepartmentTable (department_code, department_name)
select deptt_code,deptt_name+'('+ RTRIM(LTRIM(deptt_short))+')' as dept_name from m_Department
where deptt_code in (select distinct department_code from t_Project_Details where district_id=#DistrictId
and financial_year=#yr);
--Insert into Project Table With Corresponding Department Name & Code
insert into #ProjectTable (
department_code,
project_code,
project_name,
department_name,
district_code,
district_name,
tehsil_code,
tehsil_name,
service_code,
[service_name],
sector_code,
sector_name,
project_start_year,
project_compl_year,
financial_year
)
SELECT pd.department_code,
pd.project_Code,
pd.project_name,
d.deptt_name,
pd.district_id,
di.district_name,
pd.tehsil_id,
t.tehsil_name,
pd.service_code,
s.[service_name],
pd.sector_code,
se.sector_name,
CONVERT(varchar,YEAR(pd.project_initiation_fin_from_yr)) + ' ' + CONVERT(varchar(3),pd.project_initiation_fin_from_yr,100) as project_start_year,
CONVERT(varchar,YEAR(pd.project_initiation_fin_to_yr)) + ' ' + CONVERT(varchar(3),pd.project_initiation_fin_to_yr,100) as project_compl_year,
pd.financial_year
FROM t_Project_Details pd
INNER JOIN m_Department d
ON d.deptt_code=pd.department_code
INNER JOIN m_Service s
ON s.service_code = pd.service_code
INNER JOIN m_Sector se
ON se.sector_code=pd.sector_code
INNER JOIN m_District di
ON di.district_code=pd.district_id
INNER JOIN m_Tehsil t
ON t.tehsil_code = pd.tehsil_id
WHERE
district_id=#DistrictId and
financial_year=#yr;
--select all from Department Table;
select * from #ProjectTable;
END
Query Result Image: https://drive.google.com/open?id=0Bxn7UXgmstmRaS1qX21kbjlwZzg
Required Output Image: https://drive.google.com/open?id=0Bxn7UXgmstmRekJkUWhBcmNCbk0
Your required output is a presentation layer issue; SQL can return your results but cannot make one row contain one thing and following rows contain many different things in a different format.
A SQL resultset will contain the same number of columns in all rows each with the same datatype.
Use something like SSRS to acheive your desire output.
I have iPhone APP which was released today. Data for the app is coming from Database. While testing I noticed for one of the SPs which returns Dataset having 4 tables from Table to Table3. Table3 some time does not exist depending on the WHERE claus for some of the Client. Inside the app I have assumed it is present so result I am getting is in the for of dictionary of array. I am directly checking for ObjectATIndex. When table does not return condition fail and App crash.
Since App released today itself I cannot change code as of now.
Can I send some default values inside table.
Suppose my query for the table is
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- ALTER date: <ALTER Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[_spGetEmpList]
#strComCode as varchar(50),
#iDepID as INT,
#strType AS varchar(20)
AS
BEGIN
DECLARE #bNameOrder as bit
SET NOCOUNT ON;
SELECT #bNameOrder = dbo.svnGetSetupOption(#iDepID,
'LastNamePreceedsFirstName',
#strComCode)
IF ( #bNameOrder IS NULL )
SET #bNameOrder = 0
IF(#strType = 'Emp')
BEGIN
--0**************************************
SELECT EmpID AS ResourceID, EmpNumber
FROM Emuloyeetbl
WHERE Emuloyeetbl.IsActive = 1 AND DepID = #iDepID
ORDER BY EmpFName
--1**************************************
SELECT DepartmentName
FROM tblDepartment
WHERE IsActive = 1
--2**************************************
SELECT OptionValue AS EmpRole
FROM EmpRole
WHERE OptionName = 'EmployeeRole' AND DepID = #iDepID AND IsActive = 1
--3**************************************
Select EmployeeFirstName + ' '+EmplouyeeLastName as EmpName
from EmpTable
Where DepID = #iDepID AND EmpSalary < 10
END
END
Above query does not return any rows, but inside my app I am checking for table(I assumed table will be present), is there any way I can check if row
exist or not if not then send some empty value for EmpName, at least app will not Crach.....
I dont think this is a good solution overall. Seeing that you are stuck, maybe this will work for you.
Create Table #EmpTable (EmployeeFirstName Varchar(8000), EmployeeLastName Varchar(8000), EmpSalary Decimal(15,2))
Insert #EmpTable Values ('Jill', 'Jacobs', 20000)
Insert #EmpTable Values ('Joe', 'Johnson', 60000)
The query looks like this:
If Exists(Select null from #EmpTable Where EmpSalary < #Filter)
Select EmployeeFirstName + ' '+EmployeeLastName as EmpName from #EmpTable Where EmpSalary < #Filter
Else
Select '' as EmpName
-- If looking for less than 10 a blank row is returned.
Declare #Filter Decimal = 10
If Exists(Select null from #EmpTable Where EmpSalary < #Filter)
Select EmployeeFirstName + ' '+EmployeeLastName as EmpName from #EmpTable Where EmpSalary < #Filter
Else
Select '' as EmpName
-- This returns the record for Jill Jacobs
Declare #Filter Decimal = 30000
If Exists(Select null from #EmpTable Where EmpSalary < #Filter)
Select EmployeeFirstName + ' '+EmployeeLastName as EmpName from #EmpTable Where EmpSalary < #Filter
Else
Select '' as EmpName
i have not created any table, but as Joe C mentioned i have used If Exists.
simple way:
IF EXISTS( Select EmployeeFirstName + ' '+EmplouyeeLastName as EmpName
from EmpTable
Where DepID = #iDepID AND EmpSalary < 10)
BEGIN
Select EmployeeFirstName + ' '+EmplouyeeLastName as EmpName
from EmpTable
Where DepID = #iDepID AND EmpSalary < 10
ORDER BY EmpName
END
ELSE
BEGIN
SELECT '' AS EmpName
END
Thank you Joe C for quick help.
This is an alternative answer with CTE:
CREATE TABLE EmpTable( EmployeeFirstName VARCHAR( 10 ), EmplouyeeLastName VARCHAR( 10 ), EmpSalary INT )
INSERT INTO EmpTable
VALUES
( 'John', 'Smith', 9 ),
( 'Bob', 'Smith', 11 )
DECLARE #MaxSalary INT
SET #MaxSalary = 7
;WITH EmpTable2 (EmpName)
AS
(
SELECT EmployeeFirstName + ' '+EmplouyeeLastName as EmpName
FROM EmpTable
WHERE EmpSalary < #MaxSalary
)
SELECT *
FROM EmpTable2
/* Add Dummy row when no records have been returned by CTE */
UNION ALL
SELECT 'None' AS EmpName
WHERE NOT EXISTS( SELECT * FROM EmpTable2 )
The above code puts a CTE around your original query. The part following UNION ALL conditionally adds a "Dummy" row if no records have been returned by CTE.
Another way:
SELECT EmpName
FROM
( SELECT EmpName, COUNT(*) OVER() AS Cnt
FROM
( SELECT EmployeeFirstName + ' ' + EmplouyeeLastName AS EmpName
FROM EmpTable
WHERE EmpSalary < #MaxSalary
UNION ALL
SELECT 'None' AS EmpName
) AS a
) AS b
WHERE ( Cnt > 1 AND EmpName != 'None' ) OR Cnt = 1
This question already has answers here:
Parameterize an SQL IN clause
(41 answers)
Closed 7 years ago.
If you have two table Employee and Department.
tblEmp - EmpID, EmpName,DeptID are the fields
tblDepartment - DeptID,DeptName are the fields
Employee and Department table have the foreign key relation.
SELECT * FROM tblEmp e
INNER JOIN tblDepartment d on d.DeptID = e.DeptID
WHERE d.DeptID IN ('1','2')
How to write stored procedure for above statement?
The department id values in where clause IN statement are dynamic (1,2) or (1,2,3) what ever I will pass them dynamically.
You can pass all values in single varchar(max) object.
Then in your sp, you can split your values by using split function and then put 'IN' clause on it.
Create procedure sp_test
#var1 nvarchar(max)
as
begin
select * from tblEmp e
Inner join tblDepartment d on d.DeptID = e.DeptID
where d.DeptID IN select value from dbo.split(#var1))
end
create a function to split the comma separated values as below,
CREATE FUNCTION [dbo].[FnSplit]
(
#List nvarchar(2000),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(100)
)
AS
BEGIN
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
In your Stored Procedure call the function as below,
CREATE PROCEDURE usp_getvalues
#var1 nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM tblEmp e
INNER JOIN tblDepartment d
on d.DeptID = e.DeptID
WHERE d.DeptID IN (SELECT value FROM [dbo].[FnSplit](#var1))
SET NOCOUNT OFF;
END
Consider a column named EmployeeName table Employee. The goal is to delete repeated records, based on the EmployeeName field.
EmployeeName
------------
Anand
Anand
Anil
Dipak
Anil
Dipak
Dipak
Anil
Using one query, I want to delete the records which are repeated.
How can this be done with TSQL in SQL Server?
You can do this with window functions. It will order the dupes by empId, and delete all but the first one.
delete x from (
select *, rn=row_number() over (partition by EmployeeName order by empId)
from Employee
) x
where rn > 1;
Run it as a select to see what would be deleted:
select *
from (
select *, rn=row_number() over (partition by EmployeeName order by empId)
from Employee
) x
where rn > 1;
Assuming that your Employee table also has a unique column (ID in the example below), the following will work:
delete from Employee
where ID not in
(
select min(ID)
from Employee
group by EmployeeName
);
This will leave the version with the lowest ID in the table.
Edit
Re McGyver's comment - as of SQL 2012
MIN can be used with numeric, char, varchar, uniqueidentifier, or datetime columns, but not with bit columns
For 2008 R2 and earlier,
MIN can be used with numeric, char, varchar, or datetime columns, but not with bit columns (and it also doesn't work with GUID's)
For 2008R2 you'll need to cast the GUID to a type supported by MIN, e.g.
delete from GuidEmployees
where CAST(ID AS binary(16)) not in
(
select min(CAST(ID AS binary(16)))
from GuidEmployees
group by EmployeeName
);
SqlFiddle for various types in Sql 2008
SqlFiddle for various types in Sql 2012
You could try something like the following:
delete T1
from MyTable T1, MyTable T2
where T1.dupField = T2.dupField
and T1.uniqueField > T2.uniqueField
(this assumes that you have an integer based unique field)
Personally though I'd say you were better off trying to correct the fact that duplicate entries are being added to the database before it occurs rather than as a post fix-it operation.
DELETE
FROM MyTable
WHERE ID NOT IN (
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)
WITH TempUsers (FirstName, LastName, duplicateRecordCount)
AS
(
SELECT FirstName, LastName,
ROW_NUMBER() OVER (PARTITIONBY FirstName, LastName ORDERBY FirstName) AS duplicateRecordCount
FROM dbo.Users
)
DELETE
FROM TempUsers
WHERE duplicateRecordCount > 1
WITH CTE AS
(
SELECT EmployeeName,
ROW_NUMBER() OVER(PARTITION BY EmployeeName ORDER BY EmployeeName) AS R
FROM employee_table
)
DELETE CTE WHERE R > 1;
The magic of common table expressions.
Try
DELETE
FROM employee
WHERE rowid NOT IN (SELECT MAX(rowid) FROM employee
GROUP BY EmployeeName);
If you're looking for a way to remove duplicates, yet you have a foreign key pointing to the table with duplicates, you could take the following approach using a slow yet effective cursor.
It will relocate the duplicate keys on the foreign key table.
create table #properOlvChangeCodes(
id int not null,
name nvarchar(max) not null
)
DECLARE #name VARCHAR(MAX);
DECLARE #id INT;
DECLARE #newid INT;
DECLARE #oldid INT;
DECLARE OLVTRCCursor CURSOR FOR SELECT id, name FROM Sales_OrderLineVersionChangeReasonCode;
OPEN OLVTRCCursor;
FETCH NEXT FROM OLVTRCCursor INTO #id, #name;
WHILE ##FETCH_STATUS = 0
BEGIN
-- determine if it should be replaced (is already in temptable with name)
if(exists(select * from #properOlvChangeCodes where Name=#name)) begin
-- if it is, finds its id
Select top 1 #newid = id
from Sales_OrderLineVersionChangeReasonCode
where Name = #name
-- replace terminationreasoncodeid in olv for the new terminationreasoncodeid
update Sales_OrderLineVersion set ChangeReasonCodeId = #newid where ChangeReasonCodeId = #id
-- delete the record from the terminationreasoncode
delete from Sales_OrderLineVersionChangeReasonCode where Id = #id
end else begin
-- insert into temp table if new
insert into #properOlvChangeCodes(Id, name)
values(#id, #name)
end
FETCH NEXT FROM OLVTRCCursor INTO #id, #name;
END;
CLOSE OLVTRCCursor;
DEALLOCATE OLVTRCCursor;
drop table #properOlvChangeCodes
delete from person
where ID not in
(
select t.id from
(select min(ID) as id from person
group by email
) as t
);
Please see the below way of deletion too.
Declare #Employee table (EmployeeName varchar(10))
Insert into #Employee values
('Anand'),('Anand'),('Anil'),('Dipak'),
('Anil'),('Dipak'),('Dipak'),('Anil')
Select * from #Employee
Created a sample table named #Employee and loaded it with given data.
Delete aliasName from (
Select *,
ROW_NUMBER() over (Partition by EmployeeName order by EmployeeName) as rowNumber
From #Employee) aliasName
Where rowNumber > 1
Select * from #Employee
Result:
I know, this is asked six years ago, posting just incase it is helpful for anyone.
Here's a nice way of deduplicating records in a table that has an identity column based on a desired primary key that you can define at runtime. Before I start I'll populate a sample data set to work with using the following code:
if exists (select 1 from sys.all_objects where type='u' and name='_original')
drop table _original
declare #startyear int = 2017
declare #endyear int = 2018
declare #iterator int = 1
declare #income money = cast((SELECT round(RAND()*(5000-4990)+4990 , 2)) as money)
declare #salesrepid int = cast(floor(rand()*(9100-9000)+9000) as varchar(4))
create table #original (rowid int identity, monthyear varchar(max), salesrepid int, sale money)
while #iterator<=50000 begin
insert #original
select (Select cast(floor(rand()*(#endyear-#startyear)+#startyear) as varchar(4))+'-'+ cast(floor(rand()*(13-1)+1) as varchar(2)) ), #salesrepid , #income
set #salesrepid = cast(floor(rand()*(9100-9000)+9000) as varchar(4))
set #income = cast((SELECT round(RAND()*(5000-4990)+4990 , 2)) as money)
set #iterator=#iterator+1
end
update #original
set monthyear=replace(monthyear, '-', '-0') where len(monthyear)=6
select * into _original from #original
Next I'll create a Type called ColumnNames:
create type ColumnNames AS table
(Columnnames varchar(max))
Finally I will create a stored proc with the following 3 caveats:
1. The proc will take a required parameter #tablename that defines the name of the table you are deleting from in your database.
2. The proc has an optional parameter #columns that you can use to define the fields that make up the desired primary key that you are deleting against. If this field is left blank, it is assumed that all the fields besides the identity column make up the desired primary key.
3. When duplicate records are deleted, the record with the lowest value in it's identity column will be maintained.
Here is my delete_dupes stored proc:
create proc delete_dupes (#tablename varchar(max), #columns columnnames readonly)
as
begin
declare #table table (iterator int, name varchar(max), is_identity int)
declare #tablepartition table (idx int identity, type varchar(max), value varchar(max))
declare #partitionby varchar(max)
declare #iterator int= 1
if exists (select 1 from #columns) begin
declare #columns1 table (iterator int, columnnames varchar(max))
insert #columns1
select 1, columnnames from #columns
set #partitionby = (select distinct
substring((Select ', '+t1.columnnames
From #columns1 t1
Where T1.iterator = T2.iterator
ORDER BY T1.iterator
For XML PATH ('')),2, 1000) partition
From #columns1 T2 )
end
insert #table
select 1, a.name, is_identity from sys.all_columns a join sys.all_objects b on a.object_id=b.object_id
where b.name = #tablename
declare #identity varchar(max)= (select name from #table where is_identity=1)
while #iterator>=0 begin
insert #tablepartition
Select distinct case when #iterator=1 then 'order by' else 'over (partition by' end ,
substring((Select ', '+t1.name
From #table t1
Where T1.iterator = T2.iterator and is_identity=#iterator
ORDER BY T1.iterator
For XML PATH ('')),2, 5000) partition
From #table T2
set #iterator=#iterator-1
end
declare #originalpartition varchar(max)
if #partitionby is null begin
select #originalpartition = replace(b.value+','+a.type+a.value ,'over (partition by','') from #tablepartition a cross join #tablepartition b where a.idx=2 and b.idx=1
select #partitionby = a.type+a.value+' '+b.type+a.value+','+b.value+') rownum' from #tablepartition a cross join #tablepartition b where a.idx=2 and b.idx=1
end
else
begin
select #originalpartition=b.value +','+ #partitionby from #tablepartition a cross join #tablepartition b where a.idx=2 and b.idx=1
set #partitionby = (select 'OVER (partition by'+ #partitionby + ' ORDER BY'+ #partitionby + ','+b.value +') rownum'
from #tablepartition a cross join #tablepartition b where a.idx=2 and b.idx=1)
end
exec('select row_number() ' + #partitionby +', '+#originalpartition+' into ##temp from '+ #tablename+'')
exec(
'delete a from _original a
left join ##temp b on a.'+#identity+'=b.'+#identity+' and rownum=1
where b.rownum is null')
drop table ##temp
end
Once this is complied, you can delete all your duplicate records by running the proc. To delete dupes without defining a desired primary key use this call:
exec delete_dupes '_original'
To delete dupes based on a defined desired primary key use this call:
declare #table1 as columnnames
insert #table1
values ('salesrepid'),('sale')
exec delete_dupes '_original' , #table1