I had a stored procedure which has to be input with more than 8000 rows at a single button click that is used to close the daily attendance of employees.
I plan to send the input to stored procedure as datatable rather than sending it as row by row each time
I managed to create a table type user-defined type and used a parameter with that user-defined type as input parameter
USE [ATCHRM.MDF]
GO
/****** Object: UserDefinedTableType [dbo].[employeeswipedclose123] Script Date: 12/11/2012 12:04:34 ******/
CREATE TYPE [dbo].[employeeswipedclose123] AS TABLE(
[empid] [int] NULL,
[datetoday] [datetime] NULL,
[Swipepk] [int] NULL
)
GO
CREATE PROCEDURE dbo.CloseAttendance (@closingemployee dbo.employeeswipedclose123 READONLY )
AS
BEGIN
MERGE EmployeSwipeDaily_tbl AS Target
USING @closingemployee AS Source
ON (Target.empid = Source.empid) and (Target.Date = Source.datetoday)
WHEN MATCHED THEN
BEGIN
UPDATE Target
SET Target. IsCompleted = N'Y'
WHERE (Source.swipePK = Target.Swipepk) AND (Source.empid = Target.empid) AND (Target.Date = Source.datetoday)
WHEN NOT MATCHED THEN
INSERT INTO Target
(empid, Swipin, SwipeOut, Date, Duration, deviceid, InStatus, Outstatus, Invalue, OutValue, IsCompleted, CompletedDate)
VALUES (@empid, CONVERT(DATETIME, ' 00:00:00', 102), CONVERT(DATETIME, ' 00:00:00', 102),@datetoday, CONVERT(DATETIME,
' 00:00:00', 102), 0, N'A', N'A', 0, 0, N'Y',(select GETDATE()) )
END
GO
but now what I want is inside the stored procedure I want to loop the Datatable and check a condition
eg like this
for(int i=0 ;i<dt.count;i++)
{
if(dt.rows[i][swipepk]==0)
{
insert into employe swipe tbl()
}
else
{
update employee tbl
}
}
Can anyone suggest a better solution to loop a datatable in a stored procedure?
Since you’re on SQL Server 2008 – this is exactly the scenario for using the
MERGEstatement! No looping or anything needed – just a singleMERGEstatement will do!Of course, you can also do other things – and you can define more matching/non-matching criteria, if needed.
This
MERGEstatement is run once and does all the work in a single pass – no looping, no RBAR (row-by-agonizing-row) processing – nothing of that sort. One nice, fast, set-based statement and you’re done!Update: from your updated question, I see you have three major errors in your
MERGEstatement: