I've tried to focus on just the portion of my main query giving me trouble. This query is being used to populate an SSRS report which has an optional date parameter. This query snippet is used in a LEFT Join. If no date is specified, all matching records should be returned. That seems to work. But if I specify a date and no records are returned in the second column, no results for that row should be displayed. Not sure if I explained that well.
Here is the snippet:
DECLARE #DispoStartDt datetime, #DispoEndDt datetime, #DispoCode varchar(800)
SET #DispoStartDt = '5-1-2050'
--SET #DispoEndDt = '12-31-2014'
SET #DispoCode = '_NULL'
SELECT c1.CaseID,
STUFF((SELECT '; ' + CONVERT(VARCHAR(10), ct.DispoDt, 101)
FROM jw50_CountInvPers ct
WHERE ct.CaseID = '00-100'
AND (ct.DispoDt >= DATEADD(dd, DATEDIFF(dd, 0, ISNULL(#DispoStartDt, ct.DispoDt)), 0) AND ct.DispoDt < DATEADD(dd, DATEDIFF(dd, -1, ISNULL(#DispoEndDt, ct.DispoDt)), 0))
ORDER BY DispoDesc
FOR XML PATH('')), 1, 1, '') [DispoDts]
FROM jw50_Case c1
WHERE c1.CaseID = '00-100'
GROUP BY c1.CaseID
My results are:
CaseID DispoDts
00-100 NULL
I want no records returned if DispoDts is NULL. Since I cannot reference a column alias, is there another way than putting this in a sub select?
EDIT:
Here is the snippet used in my Join. I'm getting rows with NULL DispoDts because of the left join. If I specify a start date, I want the results to be treated like an inner join, only return results where they match a join row. If I don't specify a date, give me everything in the main table if a join exists or not.
DECLARE #DispoStartDt datetime, #DispoEndDt datetime, #DispoCode varchar(800)
SET #DispoStartDt = '5-1-2015'
--SET #DispoEndDt = '12-31-2014'
SET #DispoCode = '_NULL'
SELECT c.CaseID
, c.ProsNum AS FileNum
, c.CaseStatusDesc AS CaseStatus
, disp.DispoDts
FROM jw50_Case c
LEFT JOIN (SELECT CaseID, DispoDts
FROM (
SELECT c1.CaseID,
STUFF((SELECT '; ' + CONVERT(VARCHAR(10), ct.DispoDt, 101)
FROM jw50_CountInvPers ct
WHERE ct.CaseID = c1.CaseId
AND (ct.DispoDt >= DATEADD(dd, DATEDIFF(dd, 0, ISNULL(#DispoStartDt, ct.DispoDt)), 0) AND ct.DispoDt < DATEADD(dd, DATEDIFF(dd, -1, ISNULL(#DispoEndDt, ct.DispoDt)), 0))
ORDER BY DispoDesc
FOR XML PATH('')), 1, 1, '') [DispoDts]
FROM jw50_Case c1
WHERE c1.CaseID = c1.CaseId
GROUP BY c1.CaseID
) a
WHERE DispoDts IS NOT NULL
) disp ON disp.CaseID = c.CaseID
ORDER BY CaseID, DispoDts
EDIT 2:
Ok, feels dirty, but it works.
WHERE (#DispoStartDt IS NULL AND #DispoEndDt IS NULL)
OR (#DispoStartDt IS NOT NULL AND #DispoEndDt IS NOT NULL AND disp.DispoDts IS NOT NULL)
OR (#DispoStartDt IS NOT NULL AND #DispoEndDt IS NULL AND disp.DispoDts IS NOT NULL)
OR (#DispoStartDt IS NULL AND #DispoEndDt IS NOT NULL AND disp.DispoDts IS NOT NULL)
You can try:
DECLARE #DispoStartDt datetime, #DispoEndDt datetime, #DispoCode varchar(800)
SET #DispoStartDt = '5-1-2050'
--SET #DispoEndDt = '12-31-2014'
SET #DispoCode = '_NULL'
SELECT CaseID,
[DispoDts]
FROM (
SELECT c1.CaseID,
STUFF((SELECT '; ' + CONVERT(VARCHAR(10), ct.DispoDt, 101)
FROM jw50_CountInvPers ct
WHERE ct.CaseID = '00-100'
AND (ct.DispoDt >= DATEADD(dd, DATEDIFF(dd, 0, ISNULL(#DispoStartDt, ct.DispoDt)), 0) AND ct.DispoDt < DATEADD(dd, DATEDIFF(dd, -1, ISNULL(#DispoEndDt, ct.DispoDt)), 0))
ORDER BY DispoDesc
FOR XML PATH('')), 1, 1, '') [DispoDts]
FROM jw50_Case c1
WHERE c1.CaseID = '00-100'
GROUP BY c1.CaseID
) as tbaux
WHERE [DispoDts] IS NOT NULL
This way you get the same values as before, but the result is passed to a query above which validates the DispoDts
And this way ?
DECLARE #DispoStartDt datetime, #DispoEndDt datetime, #DispoCode varchar(800)
SET #DispoStartDt = '5-1-2015'
--SET #DispoEndDt = '12-31-2014'
SET #DispoCode = '_NULL'
SELECT c.CaseID
, c.ProsNum AS FileNum
, c.CaseStatusDesc AS CaseStatus
, disp.DispoDts
FROM jw50_Case c
LEFT JOIN (SELECT c1.CaseID,
STUFF((SELECT '; ' + CONVERT(VARCHAR(10), ct.DispoDt, 101)
FROM jw50_CountInvPers ct
WHERE ct.CaseID = c1.CaseId
AND (ct.DispoDt >= DATEADD(dd, DATEDIFF(dd, 0, ISNULL(#DispoStartDt, ct.DispoDt)), 0) AND ct.DispoDt < DATEADD(dd, DATEDIFF(dd, -1, ISNULL(#DispoEndDt, ct.DispoDt)), 0))
ORDER BY DispoDesc
FOR XML PATH('')), 1, 1, '') [DispoDts]
FROM jw50_Case c1
WHERE c1.CaseID = c1.CaseId
GROUP BY c1.CaseID
) disp ON disp.CaseID = c.CaseID
WHERE #DispoEndDt IS NULL OR disp.DispoDts IS NOT NULL
ORDER BY CaseID, DispoDts
Related
I have a string column that contains dates. I want to convert string to date so that i can use the Date Logic ahead.
I have converted the string to DateTime but while applying the logic in the Where clause it doesn't allow me to use the Column.
SELECT a.code,
CONVERT(DATETIME,b.[FieldValue],103) as [Date1]
FROM [dbo].employeedetail as A join [dbo].CustomeFieldDetail as B
on A.Id = B.EMployeeid
WHERE a.empstatus = 1
AND B.CustomeFieldName = 'PASSPORT' AND
( Datediff(dd, Getdate(), Dateadd(yyyy, Datediff(yyyy, b.[Date1],
Getdate())
+
1, b.[Date1]))
+ 1 ) % 366 = 50
Can anyone help me?
Use APPLY to introduce a reusable expression.
SELECT a.code,
c.[Date1]
FROM [dbo].employeedetail as A
JOIN [dbo].CustomeFieldDetail as B ON A.Id = B.EMployeeid
CROSS APPLY (
SELECT CONVERT(DATETIME,b.[FieldValue],103) as [Date1]
) c
WHERE a.empstatus = 1
AND B.CustomeFieldName = 'PASSPORT' AND
( Datediff(dd, Getdate(), Dateadd(yyyy, Datediff(yyyy, c.[Date1],
Getdate())
+
1, c.[Date1]))
+ 1 ) % 366 = 50
A better solution is store dates as DATE, DATETIME, not strings.
Using CTE results in an even more compact query:
WITH B AS (
SELECT *, CONVERT(DATETIME, [FieldValue], 103) AS [Date1]
FROM [dbo].CustomeFieldDetail
WHERE (CustomeFieldName = 'PASSPORT')
)
SELECT A.code, B.[Date1]
FROM [dbo].EmployeeDetail AS A JOIN B ON A.Id = B.EMployeeid
WHERE (A.empstatus = 1)
AND (((DATEDIFF(dd, GETDATE(),
DATEADD(yyyy, DATEDIFF(yyyy, B.[Date1], GETDATE()) + 1, B.[Date1])) + 1)
% 366) = 50)
I have been displaying Day Wise Attendance Data with Pivot SQL.
declare #startdate datetime = '2016-09-26'
declare #enddate datetime = '2016-10-01'
declare #CompanyID int = 1
DECLARE #COLUMN VARCHAR(MAX), #SQL NVARCHAR(MAX);
SET #COLUMN = N'';
DECLARE #DATERANGE TABLE (DateToCheck DATE)
;WITH Temp
AS
(
SELECT DT =DATEADD(DD,0, #startdate)
WHERE DATEADD(DD, 1, #startdate) <= #enddate
UNION ALL
SELECT DATEADD(DD, 1, DT)
FROM Temp
WHERE DATEADD(DD, 1, DT) <= #enddate
)
INSERT INTO #DATERANGE
SELECT DT From Temp
SELECT #COLUMN += N', T.' + QUOTENAME(DateRanges) FROM (SELECT CAST(CONVERT(DATE, T.DateToCheck) AS VARCHAR(10)) AS DateRanges FROM #DATERANGE T group by T.DateToCheck) AS A;
SET #SQL = '
DECLARE #DATERANGE TABLE (DateToCheck DATE)
;WITH Temp
AS
(
SELECT DT =DATEADD(DD,0, #startdate)
WHERE DATEADD(DD, 1, #startdate) <= #enddate
UNION ALL
SELECT DATEADD(DD, 1, DT)
FROM Temp
WHERE DATEADD(DD, 1, DT) <= #enddate
)
INSERT INTO #DATERANGE
SELECT DT From Temp
SELECT *
FROM (
SELECT E.FirstName, E.LastName, E.Email, T.DateToCheck, COALESCE(A.val, L.val, H.val, ''Absent'') val
FROM AspNetUsers E
CROSS APPLY (
SELECT DateToCheck FROM #DATERANGE
) T--(DateToCheck)
LEFT JOIN (SELECT ''Holiday'' val, HolidayDate, CompanyID FROM Holidays) H ON H.HolidayDate = T.DateToCheck AND H.CompanyID = #CompanyID
LEFT JOIN (SELECT ''In : '' + CONVERT(VARCHAR, MIN(AttendanceDateTime), 108) + '' / Out : '' + CONVERT(VARCHAR, MAX(AttendanceDateTime), 108) val, CAST(AttendanceDateTime As DATE) As AttendanceDate, UserID FROM Attendances GROUP BY CAST(AttendanceDateTime As DATE), UserID) A ON A.AttendanceDate = T.DateToCheck AND A.UserID = E.Id
LEFT JOIN (SELECT ''Leave'' val, LeaveDate, UserID FROM LeaveApplications) L ON L.LeaveDate = T.DateToCheck AND L.UserID = E.Id
WHERE E.CompanyID = #CompanyID
) T
PIVOT (MAX(val) FOR DateToCheck IN (' + STUFF(REPLACE(#COLUMN, ', T.[', ',['), 1, 1, '') + ')) P';
EXEC sp_executesql #SQL, N'#startdate DATE, #enddate DATE, #CompanyID INT', #startdate, #enddate, #CompanyID
And below is the result set of how it's now
Now I wish to add more field to the above SQL to display counts like PresentCount, AbsentCount, HolidayCount and LeaveCount
I have already written a SQL where I could easily display these counts but, I'm unable to make it work with the above PIVOT SQL.
So in this case, the result for first row would be PresentCount = 0, AbsentCount = 6, HolidayCount = 0 and LeaveCount = 0. For Row 2 it would be PresentCount = 4, AbsentCount = 2, LeaveCount and HolidayCount both is 0.
I am attempting to update a stored procedure and have added u.DIVISION in the code however I am not getting the error message
Column name or number of supplied values does not match table definition.
Any suggestions on what I might be missing?
SET ansi_nulls ON
go
SET quoted_identifier ON
go
ALTER PROCEDURE [dbo].[Slx_activity]
AS
DECLARE #ReportStartDate DATETIME,
#ReportEndDate DATETIME
DECLARE #Today DATETIME
SET #Today = Getdate()
DECLARE #Diff INT
SET #Diff = Datediff(day, Dateadd(day, 5, 0), #Today)
SET #ReportEndDate = Dateadd(day, #Diff - #Diff % 7, Dateadd(day, 5, 0))
SET #ReportStartDate = Datediff(day, 6, #ReportEndDate)
IF Object_id('SLXActivity', 'U') IS NOT NULL
DROP TABLE slxactivity;
SELECT ' Current Activity:' + ' ' + p.[text] AS [TYPE],
h.createdate,
p.[text],
h.[description],
h.startdate,
Cast (NULL AS DATETIME) AS COMPLETEDDATE,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
h.userid,
h.accountid,
h.contactid,
h.opportunityid
INTO slxactivity
FROM [SalesLogix_Production].[sysdba].[activity] h
LEFT JOIN [SalesLogix_Production].[sysdba].[picklist] p
ON h.[type] = p.id
WHERE p.[text] NOT IN ( 'Personal Activity' )
AND Cast(h.startdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT ' Completed Activity:' + ' ' + p.[text] AS [TYPE],
h.createdate,
p.[text],
h.[description],
h.startdate,
h.completeddate,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
h.userid,
h.accountid,
h.contactid,
h.opportunityid
FROM (SELECT accountid,
[description],
Min(historyid) AS HISTORYID,
completeddate
FROM [SalesLogix_Production].[sysdba].[history]
GROUP BY accountid,
[description],
completeddate) a1
LEFT JOIN [SalesLogix_Production].[sysdba].[history] h
ON a1.accountid = h.accountid
AND a1.historyid = h.historyid
LEFT JOIN [SalesLogix_Production].[sysdba].[picklist] p
ON h.[type] = p.id
WHERE p.[text] NOT IN ( 'Personal Activity' )
AND Cast(h.completeddate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT 'Opportunity Added' AS [TYPE],
o.createdate,
o.status AS [TEXT],
NULL AS [DESCRIPTION],
o.estimatedclose AS STARTDATE,
NULL AS COMPLETEDDATE,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
o.createuser,
o.accountid,
NULL AS CONTACTID,
o.opportunityid
FROM [SalesLogix_Production].[sysdba].[opportunity] o
WHERE Cast(o.createdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT 'Contact Added' AS [TYPE],
c.createdate,
NULL AS [TEXT],
NULL AS [DESCRIPTION],
NULL AS STARTDATE,
NULL AS COMPLETEDDATE,
NULL AS BIDNUMBER_STATIC,
NULL AS BID_STATUS,
c.createuser,
c.accountid,
c.contactid,
u.division,
NULL AS OPPORTUNITYID
FROM [SalesLogix_Production].[sysdba].[contact] c
LEFT JOIN [SalesLogix_Production].[sysdba].[userinfo] u
ON c.createuser = u.userid
LEFT JOIN [SalesLogix_Production].[sysdba].[usersecurity] us
ON u.userid = us.userid
WHERE Cast(c.createdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT 'Account Created' AS [TYPE],
a.createdate,
a.type AS [TEXT],
a.industry AS [DESCRIPTION],
NULL AS STARTDATE,
NULL AS COMPLETEDDATE,
NULL AS BIDNUMBER_STATIC,
NULL AS BID_STATUS,
a.createuser,
a.accountid,
NULL AS CONTACTID,
NULL AS OPPORTUNITYID
FROM [SalesLogix_Production].[sysdba].[account] a
WHERE Cast(a.createdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
SELECT t.[type],
t.createdate,
t.[text],
u.username,
a.account,
c.lastname + ', ' + c.firstname AS [CONTACT],
o.[description] AS OPPORTUNITY,
oe.bidnumber_static,
oe.bid_status,
t.[description],
t.startdate,
t.completeddate,
u.division,
#ReportStartDate AS ReportStartDate,
#ReportEndDate AS ReportEndDate
FROM [SalesLogix_Production].[sysdba].[userinfo] u
JOIN [SalesLogix_Production].[sysdba].[usersecurity] us
ON u.userid = us.userid
LEFT JOIN slxactivity t
ON u.userid = t.userid
LEFT JOIN [SalesLogix_Production].[sysdba].[account] a
ON t.accountid = a.accountid
LEFT JOIN [SalesLogix_Production].[sysdba].[contact] c
ON t.contactid = c.contactid
LEFT JOIN [SalesLogix_Production].[sysdba].[opportunity] o
ON t.opportunityid = o.opportunityid
LEFT JOIN [SalesLogix_Production].[sysdba].[c_opportunity_ext] oe
ON t.opportunityid = oe.opportunityid
WHERE us.[type] NOT IN ( 'R', 'W' )
AND u.username <> 'svc_slxadmin'
You need to specify the column in the first statement which creates the table:
SELECT ' Current Activity:' + ' ' + p.[text] AS [TYPE],
h.createdate,
p.[text],
h.[description],
h.startdate,
Cast (NULL AS DATETIME) AS COMPLETEDDATE,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
h.userid,
h.accountid,
h.contactid,
CAST(NULL AS VARCHAR(100)) AS division,
/*
you need to specify/select the column here, with the relevant
type, in this context. I assumed it's a string just for the example.
*/
h.opportunityid
INTO slxactivity
FROM [SalesLogix_Production].[sysdba].[activity] h
LEFT JOIN [SalesLogix_Production].[sysdba].[picklist] p
ON h.[type] = p.id
WHERE p.[text] NOT IN ( 'Personal Activity' )
AND Cast(h.startdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
I am passing 3 parameters into my stored procedure: #Time, #DeptID, #Value.
#Time is representing: 1=past 24hours, 2=past week, 3=past month, 4=past year
#DeptID is the ID of the various departments
#Value 1=Sort by Low, 2=Sort by High
Here is my current code:
DECLARE #SQL VARCHAR(MAX)
SET #SQL = ('SELECT S.ID, S.[Description], D.Department, S.Value, S.[Date] FROM Suggestions S INNER JOIN Department D ON D.ID = S.DeptID WHERE Approved =1')
IF (#DeptID = 0 AND #Value = 0 AND #Time = 0)
BEGIN
SET #SQL = (#SQL +' ORDER BY [Date] DESC')
END
IF (#Time > 0)
BEGIN
SET #SQL = (CASE WHEN #Time = 1 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -1, GETDATE()) ORDER BY S.[Date] DESC')
WHEN #Time = 2 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -7, GETDATE()) ORDER BY S.[Date] DESC' )
WHEN #Time = 3 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -30, GETDATE()) ORDER BY S.[Date] DESC')
WHEN #Time = 4 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -365, GETDATE()) ORDER BY S.[Date] DESC') END)
END
IF (#DeptID > 0)
BEGIN
SET #SQL = #SQL + ' AND S.DeptID = #DeptID ORDER BY S.[Date] DESC')
END
IF (#Value > 0)
BEGIN
SET #SQL = (CASE WHEN #Value = 1 THEN (#SQL + ' ORDER BY S.Value DESC')
WHEN #Value = 2 THEN (#SQL + ' ORDER BY S.Value ASC')
This is fine when only one parameter is passed in, but when trying to filter by two or more parameters then I run into a problem...
So far I have been getting errors because I am adding 2 'Order By' clause onto the end of my Statement:
ORDER BY S.[Date] DESC ORDER BY S.Value DESC
Can anyone point me in the right direction with this?
Any help at all would be much appriciated
I rewrote your code to not use dynamic SQL:
SELECT S.ID,
S.[Description],
D.Department,
S.Value,
S.[Date]
FROM Suggestions S
INNER JOIN Department D
ON D.ID = S.DeptID
WHERE Approved =1
AND (#Time = 0
OR (#Time = 1 AND [Date] >= DATEADD(DAY, -1, GETDATE()))
OR (#Time = 2 AND [Date] >= DATEADD(DAY, -30, GETDATE()))
OR (#Time = 3 AND [Date] >= DATEADD(DAY, -365, GETDATE()))
)
AND (#DeptID = 0
OR (#DeptID > 0 AND S.DeptID = #DeptID)
)
ORDER BY [Date] DESC,
CASE WHEN #Value = 1 THEN S.Value
ELSE 1 END DESC,
CASE WHEN #Value = 2 THEN S.Value
ELSE 1 END ASC
Updated with dynamic SQL version
Ok, if you want the dynamic SQL solution, then this is one way (but first, did you read this link?):
DECLARE #SQL VARCHAR(MAX), #WHERE VARCHAR(MAX), #ORDER VARCHAR(MAX)
SET #SQL = ('SELECT S.ID, S.[Description], D.Department, S.Value, S.[Date] FROM Suggestions S INNER JOIN Department D ON D.ID = S.DeptID WHERE Approved =1')
SET #WHERE = ' AND ' +
CASE WHEN #Time = 0 THEN '1 = 1'
WHEN #Time = 1 THEN '[Date] >= DATEADD(DAY, -1, GETDATE())'
WHEN #Time = 2 THEN '[Date] >= DATEADD(DAY, -7, GETDATE())'
WHEN #Time = 3 THEN '[Date] >= DATEADD(DAY, -30, GETDATE())'
WHEN #Time = 4 THEN '[Date] >= DATEADD(DAY, -365, GETDATE())' END
SET #WHERE = #WHERE +
CASE WHEN #DeptID > 0 THEN ' AND S.DeptID = #DeptID'
ELSE '' END
SET #ORDER = ' ORDER BY S.[Date] DESC' +
CASE WHEN #Value = 0 THEN ''
WHEN #Value = 1 THEN ', S.Value DESC'
WHEN #Value = 2 THEN ', S.Value ASC' END
SET #SQL = #SQL + #WHERE + #ORDER
PRINT #SQL
Not sure I agree with all of your dynamic SQL but why not just check if the order by clause is already in the SQL String and if it is just add the additional parameter otherwise add the entire clause. You can do this using CharIndex.
I would also suggest only adding the DESC at the very end just before you execute the #SQL
IF (#DeptID = 0 AND #Value = 0 AND #Time = 0)
BEGIN
IF CHARINDEX('ORDER BY',#SQL) = 0
BEGIN
SET #SQL = (#SQL +' ORDER BY [Date] ')
END
ELSE
BEGIN
SET #SQL = (#SQL +',[Date] ')
END
END
SET #SQL = #SQL + ' DESC'
DECLARE #STARTDATE datetime = CASE #Time
WHEN 1 THEN DATEADD(dd, -1, GETDATE())
WHEN 2 THEN DATEADD(ww, -1, GETDATE())
WHEN 3 THEN DATEADD(mm, -1, GETDATE())
WHEN 4 THEN DATEADD(yy, -1, GETDATE())
END
SELECT S.ID,
S.[Description],
D.Department,
S.Value,
S.[Date]
FROM Suggestions S INNER JOIN Department D ON D.ID = S.DeptID
WHERE Approved = 1 AND
(S.DeptID = #DeptId OR #DeptID = 0) AND
[DATEADD] >= #STARTDATE
ORDER BY case #Value when 0 then [Date] else 0 end,
case #Value when 1 then S.Value else S.Value * -1 end
it looks like the criteria for your last two if statements are being met and you're adding your order clause twice.
Try this:
DECLARE #SQL VARCHAR(MAX)
SET #SQL = ('SELECT S.ID, S.[Description], D.Department, S.Value, S.[Date] FROM Suggestions S INNER JOIN Department D ON D.ID = S.DeptID WHERE Approved =1')
IF (#DeptID = 0 AND #Value = 0 AND #Time = 0)
BEGIN
SET #SQL = (#SQL +' ORDER BY [Date] DESC')
END
IF (#Time > 0)
BEGIN
SET #SQL = (CASE WHEN #Time = 1 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -1, GETDATE()) ORDER BY S.[Date] DESC')
WHEN #Time = 2 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -7, GETDATE())' )
WHEN #Time = 3 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -30, GETDATE())')
WHEN #Time = 4 THEN (#SQL + ' AND [Date] >= DATEADD(DAY, -365,GETDATE())') END)
END
IF (#DeptID > 0)
BEGIN
SET #SQL = #SQL + ' AND S.DeptID = #DeptID')
END
IF (#Value > 0)
BEGIN
SET #SQL = (CASE WHEN #Value = 1 THEN (#SQL + ' ORDER BY S.[Date] DESC, S.Value DESC')
WHEN #Value = 2 THEN (#SQL + ' ORDER BY S.[Date] ASC, S.Value ASC')
In sp here I am trying to get a count of how many records meet the criteria so that I can display as a total in the tile of the app. But am not having success with this, can you tell me how to make a count and where to put that.
(
#P_FACILITY_KEY_CSV VARCHAR(MAX)
, #DATEFROM DATETIME
, #DATETHRU DATETIME
, #P_TOTALS NUMERIC(1, 0)
)
AS
BEGIN
DECLARE #DFACKEY CHAR(4)
DECLARE #IRENEWALLCYCLEPERIOD NUMERIC
SET #IRENEWALLCYCLEPERIOD = OGEN.READ_PARAM(349, #P_FACILITY_KEY_CSV, '')
EXEC OGEN.GET_CODE_FACILITY #P_FACILITY_KEY_CSV, 'OGEN.GEN_M_DOCTOR_MAST', 'BASE', #DFACKEY OUTPUT;
IF #P_TOTALS = 1 BEGIN
SELECT P.NURSING_UNIT,
ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD) DUE_DATE,
CONVERT(NUMERIC, ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD) - GETDATE()) REMAINING
FROM OGEN.GEN_M_PATIENT_MAST P
LEFT OUTER JOIN OGEN.GEN_M_DOCTOR_MAST D ON P.PRIMARY_DOCTOR_KEY = D.DOCTOR_KEY AND D.FACILITY_KEY = #DFACKEY
LEFT OUTER JOIN OPTC.ORD_D_SCHEDULED_RECERTS SR ON P.PAT_NUMBER = - SR.PAT_NUMBER
LEFT OUTER JOIN OGEN.GEN_M_USER U ON U.USER_ID = SR.RECERT_BY
WHERE P.FACILITY_KEY IN(SELECT VALUE FROM OGEN.COMMA_TO_TABLE(#P_FACILITY_KEY_CSV))
AND DISCHARGE_DATE IS NULL
AND ( ( (#DATEFROM > 0) AND (OGEN.DATEONLY(ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD)) >= #DATEFROM) )
OR
(#DATEFROM = 0) )
AND ( ( (#DATETHRU > 0) AND (OGEN.DATEONLY(ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD)) <= #DATETHRU) )
OR
( #DATETHRU = 0) )
ORDER BY REMAINING;
END ELSE BEGIN
SELECT P.*, D.DR_FULL_NAME PRIMARY_DOCTOR_NAME,
SR.RECERT_DATE, SR.RECERT_BY, U.USER_NAME,
ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD) DUE_DATE,
CONVERT(NUMERIC, ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD) - GETDATE()) REMAINING
FROM OGEN.GEN_M_PATIENT_MAST P
LEFT OUTER JOIN OGEN.GEN_M_DOCTOR_MAST D ON P.PRIMARY_DOCTOR_KEY = D.DOCTOR_KEY AND D.FACILITY_KEY = #DFACKEY
LEFT OUTER JOIN OPTC.ORD_D_SCHEDULED_RECERTS SR ON P.PAT_NUMBER = - SR.PAT_NUMBER
LEFT OUTER JOIN OGEN.GEN_M_USER U ON U.USER_ID = SR.RECERT_BY
WHERE P.FACILITY_KEY IN(SELECT VALUE FROM OGEN.COMMA_TO_TABLE(#P_FACILITY_KEY_CSV))
AND DISCHARGE_DATE IS NULL
AND ( ( (#DATEFROM > 0) AND (OGEN.DATEONLY(ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD)) >= #DATEFROM) )
OR
(#DATEFROM = 0) )
AND ( ( (#DATETHRU > 0) AND (OGEN.DATEONLY(ISNULL( SR.USER_DEFINED_DUE_DATE, ISNULL(SR.RECERT_DATE, P.ADMIT_DATE) + #IRENEWALLCYCLEPERIOD)) <= #DATETHRU) )
OR
( #DATETHRU = 0) )
ORDER BY DUE_DATE
END
END
Do you just want an additional column in the query that is the COUNT of all records returned?
SELECT COUNT(1) OVER () Total,
.. <all your other columns> ..
Or if you can return it as the SP return value, then
RETURN ##ROWCOUNT
at the end, assuming what you have shown (the IF/SELECTs) is the end of your SP.