1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
|
ALTER PROCEDURE [dbo].[spGetWeeklyTimesheet]
@dateFROM datetime,
@dateTO datetime,
@StaffID nvarchar(5)
AS
DECLARE @sql nvarchar(max)
DECLARE @dateFROMReset datetime
DECLARE @sqlSUM nvarchar(max)
DECLARE @CustomOrder nvarchar(max)
DECLARE @CustomOrder2 nvarchar(max)
SET @dateFROMReset = @dateFROM
SET @sqlSUM = ''
SET @CustomOrder = ''
SET @CustomOrder2 = ''
WHILE @dateFROM<=@dateTo
BEGIN
SET @CustomOrder = @CustomOrder +
'case when [' + CONVERT(NVARCHAR,@dateFROM,103) + '] is null then 1 else 0 end,'
SET @CustomOrder2 = @CustomOrder2 +
'[' + CONVERT(NVARCHAR,@dateFROM,103) + '],'
SET @sqlSUM = @sqlSUm +
' sum( case when CONVERT(NVARCHAR,StartTime,103) = ''' + CONVERT(NVARCHAR,@dateFROM,103) + ''' then hours else NULL end)
as [' + CONVERT(NVARCHAR,@dateFROM,103) + '],
sum( case when CONVERT(NVARCHAR,StartTime,103) = ''' + CONVERT(NVARCHAR,@dateFROM,103) + ''' then overtime else NULL end)
as [' + CONVERT(NVARCHAR,@dateFROM,103) + '-OVER],'
IF @dateFROM = @dateTO -- remove last comma.
SET @sqlSUM = Left(@sqlSUM, Len(@sqlSUM)-1)
SET @dateFROM = @dateFROM + 1
END
SET @CustomOrder = @CustomOrder + @CustomOrder2
SET @sql = 'SELECT ' +
@sqlSUM + ', CASE
WHEN T.JobID <=0 THEN T.TenderID
ELSE T.JobID
END as JobTenderID,
CASE
WHEN T.JobID <=0 THEN Te.TenderNumber
ELSE J.Job
END as Job,
T.taskid,T.description,Tk.Task,T.JobID,T.StaffID,S.StaffFullName,Tk.SortCol,T.StartTimeExcel,T.EndTimeExcel,T.AccompaniedBy
FROM timesheet as T
LEFT JOIN Jobs as J ON T.JobID = J.ID
LEFT JOIN Tasks as Tk ON T.TaskID = Tk.ID
LEFT JOIN Tender as Te ON Te.ID = T.TenderID
LEFT JOIN Staff as S ON T.StaffID = S.ID
WHERE CONVERT(NVARCHAR,StartTime,101) >= ''' + CONVERT(NVARCHAR,@dateFROMReset,101) + '''
AND CONVERT(NVARCHAR,StartTime,101) <= ''' + CONVERT(NVARCHAR,@dateTO,101) + '''
AND T.StaffID =' + @StaffID + '
GROUP BY t.jobid,t.taskid,t.description,j.job,tk.task,T.TenderID,Te.TenderNumber,T.StaffID,S.StaffFullName,
Tk.SortCol,T.StartTimeExcel,T.EndTImeExcel,T.AccompaniedBy
ORDER BY ' + @CustomOrder + 'tk.SortCol,Job'
print @CustomOrder
exec (@sql)
|