I am new to ssrs.
I want to get all the possible data for ssrs subscribed report, which are Available in ResportServer database.
I have found some queries, but that does not have proper data. It only works for single report.
I need list of unique subscription with it's data. If possible stored procedure is preferable.
My query:
SELECT
b.name AS JobName
, e.name
, e.path
, d.description
, a.SubscriptionID
, laststatus
, eventtype
, LastRunTime
, date_created
, date_modified
FROM ReportServer.dbo.ReportSchedule a
JOIN msdb.dbo.sysjobs b
ON a.ScheduleID = b.name
JOIN ReportServer.dbo.ReportSchedule c
ON b.name = c.ScheduleID
JOIN ReportServer.dbo.Subscriptions d
ON c.SubscriptionID = d.SubscriptionID
JOIN ReportServer.dbo.Catalog e
ON d.report_oid = e.itemid
WHERE e.name = 'Sales_Report'
Thanks in advance.
I have same requirement once as like you have now...
See below stored procedure..
CREATE PROCEDURE [dbo].[GetSubscriptionData]
AS
BEGIN
SET NOCOUNT ON;
WITH
[Sub_Parameters] AS
(
SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters])
FROM [Subscriptions] a
),
[MySubscriptions] AS
(
SELECT DISTINCT [SubscriptionID], [ParameterName] = QUOTENAME(p.value('(Name)[1]', 'nvarchar(max)')), [ParameterValue] = p.value('(Value)[1]', 'nvarchar(max)')
FROM [Sub_Parameters] a
CROSS APPLY [Parameters].nodes('/ParameterValues/ParameterValue') t(p)
),
[SubscriptionsAnalysis] AS
(
SELECT a.[SubscriptionID], a.[ParameterName], [ParameterValue] =
(
SELECT STUFF((SELECT [ParameterValue] + ', ' as [text()]
FROM [MySubscriptions]
WHERE [SubscriptionID] = a.[SubscriptionID] AND [ParameterName] = a.[ParameterName]
FOR XML PATH('') ),1, 0, '') +''
)
FROM [MySubscriptions] a
GROUP BY a.[SubscriptionID],a.[ParameterName]
)
SELECT
DISTINCT (a.[SubscriptionID]),
c.[UserName] AS Owner,
b.Name,
b.Path,
a.[Locale],
a.[InactiveFlags],
d.[UserName] AS Modified_by,
a.[ModifiedDate],
a.[Description],
a.[LastStatus],
a.[EventType],
a.[LastRunTime],
a.[DeliveryExtension],
a.[Version],
sch.StartDate,
--e.[ParameterName],
--LEFT(e.[ParameterValue],LEN(e.[ParameterValue])-1) as [ParameterValue],
SUBSTRING(b.PATH,2,LEN(b.PATH)-(CHARINDEX('/',REVERSE(b.PATH))+1)) AS ProjectName
FROM
[Subscriptions] a
INNER JOIN [Catalog] AS b ON a.[Report_OID] = b.[ItemID]
Inner Join ReportSchedule as RS on rs.SubscriptionID = a.SubscriptionID
INNER JOIN Schedule AS Sch ON Sch.ScheduleID = rs.ScheduleID
LEFT OUTER JOIN [Users] AS c ON a.[OwnerID] = c.[UserID]
LEFT OUTER JOIN [Users] AS d ON a.MODIFIEDBYID = d.Userid
LEFT OUTER JOIN [SubscriptionsAnalysis] AS e ON a.SubscriptionID = e.SubscriptionID;
END
This is simplified query to get all SSRS Subscriptions
SELECT USR.UserName AS SubscriptionOwner
,SUB.ModifiedDate
,SUB.[Description]
,SUB.EventType
,SUB.DeliveryExtension
,SUB.LastStatus
,SUB.LastRunTime
,SCH.NextRunTime
,SCH.Name AS ScheduleName
,CAT.[Path] AS ReportPath
,CAT.[Description] AS ReportDescription
FROM dbo.Subscriptions AS SUB
INNER JOIN dbo.Users AS USR
ON SUB.OwnerID = USR.UserID
INNER JOIN dbo.[Catalog] AS CAT
ON SUB.Report_OID = CAT.ItemID
INNER JOIN dbo.ReportSchedule AS RS
ON SUB.Report_OID = RS.ReportID
AND SUB.SubscriptionID = RS.SubscriptionID
INNER JOIN dbo.Schedule AS SCH
ON RS.ScheduleID = SCH.ScheduleID
ORDER BY USR.UserName, CAT.[Path];
if you still have any query, comment it..
In case you need to find the sql server agent Job use this updated code
SET NOCOUNT ON;
WITH
[Sub_Parameters] AS
(
SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters])
FROM [Subscriptions] a
),
[MySubscriptions] AS
(
SELECT DISTINCT [SubscriptionID], [ParameterName] = QUOTENAME(p.value('(Name)[1]', 'nvarchar(max)')), [ParameterValue] = p.value('(Value)[1]', 'nvarchar(max)')
FROM [Sub_Parameters] a
CROSS APPLY [Parameters].nodes('/ParameterValues/ParameterValue') t(p)
),
[SubscriptionsAnalysis] AS
(
SELECT a.[SubscriptionID], a.[ParameterName], [ParameterValue] =
(
SELECT STUFF((SELECT [ParameterValue] + ', ' as [text()]
FROM [MySubscriptions]
WHERE [SubscriptionID] = a.[SubscriptionID] AND [ParameterName] = a.[ParameterName]
FOR XML PATH('') ),1, 0, '') +''
)
FROM [MySubscriptions] a
GROUP BY a.[SubscriptionID],a.[ParameterName]
)
SELECT
DISTINCT (a.[SubscriptionID]),
j.name AS SQLServerAgentJob,
c.[UserName] AS Owner,
b.Name,
b.Path,
a.[Locale],
a.[InactiveFlags],
d.[UserName] AS Modified_by,
a.[ModifiedDate],
a.[Description],
a.[LastStatus],
a.[EventType],
a.[LastRunTime],
a.[DeliveryExtension],
a.[Version],
sch.StartDate,
--e.[ParameterName],
--LEFT(e.[ParameterValue],LEN(e.[ParameterValue])-1) as [ParameterValue],
SUBSTRING(b.PATH,2,LEN(b.PATH)-(CHARINDEX('/',REVERSE(b.PATH))+1)) AS ProjectName
FROM [Subscriptions] a
INNER JOIN [Catalog] AS b ON a.[Report_OID] = b.[ItemID]
Inner Join ReportSchedule as RS on rs.SubscriptionID = a.SubscriptionID
INNER JOIN Schedule AS Sch ON Sch.ScheduleID = rs.ScheduleID
LEFT OUTER JOIN [Users] AS c ON a.[OwnerID] = c.[UserID]
LEFT OUTER JOIN [Users] AS d ON a.MODIFIEDBYID = d.Userid
LEFT OUTER JOIN [SubscriptionsAnalysis] AS e ON a.SubscriptionID = e.SubscriptionID
LEFT JOIN msdb.dbo.sysobjects so ON rs.ScheduleID= so.name
INNER JOIN msdb.dbo.sysjobs J ON CONVERT( NVARCHAR(128), RS.ScheduleID ) = J.name
INNER JOIN msdb.dbo.sysjobschedules JS ON J.job_id = JS.job_id
I am using following query to get subscriptions and then to find SQL Jobs scripts
USE ReportServer
GO
CREATE TABLE #tempReports(LogEntryId BIGINT, subscriptionid VARCHAR(1000),LastRunTime DATETIME, _Description VARCHAR(1000), ReportID VARCHAR(1000),
LastStatus VARCHAR(1000), rowNum INT)
INSERT INTO #tempReports
SELECT *
FROM
(
SELECT DISTINCT E.LogEntryId, S.subscriptionid, LastRunTime, S.Description, E.ReportID, S.LastStatus,
ROW_NUMBER() OVER(PARTITION BY E.ReportID, S.Description ORDER BY S.LastRunTime DESC) as rowNum
FROM [ExecutionLogStorage] E
INNER JOIN Subscriptions S
ON S.Report_OID = E.ReportID
WHERE 1 = 1
AND (
S.LastStatus LIKE '%has been saved to the "\\<server>\c$\SSRS_Report_Export\20%'
)
)T
WHERE rowNum = 1
ORDER BY ReportID, Description
CREATE TABLE #ExecutionStatements (ExecStatement VARCHAR(1000), job_name VARCHAR(1000), theReportOrder INT,
LogEntryId BIGINT, subscriptionid VARCHAR(1000), LastRunTime DATETIME, _Description VARCHAR(1000),
ReportID VARCHAR(1000), LastStatus VARCHAR(1000))
INSERT INTO #ExecutionStatements
SELECT 'exec sp_start_job #job_name = ''' + cast(j.name as varchar(40)) + '''' AS ExecStatement,
j.name AS job_name,
ROW_NUMBER () OVER(ORDER BY LogEntryId) AS theReportOrder,
LogEntryId, subscriptionid,LastRunTime, _Description, ReportID,
LastStatus
from msdb.dbo.sysjobs j
join msdb.dbo.sysjobsteps js
on js.job_id = j.job_id
join #tempReports s
on js.command like '%' + cast(s.subscriptionid as varchar(40)) + '%'
WHERE 1 = 1
---Execute required statements in MSDB
SELECT E.ExecStatement + '--'+ CONVERT(VARCHAR(10),E.theReportOrder), E.theReportOrder, *
FROM #ExecutionStatements E
--WHERE subscriptionid = '3AFDAC30-4F30-423F-9F72-7C04C86026AB'
ORDER BY E.theReportOrder
SELECT DISTINCT S.subscriptionid, S.Description, E.ReportID, S.LastStatus, MAX(LastRunTime) -- 2021-04-25 18:35:00.840
FROM [ExecutionLogStorage] E
INNER JOIN Subscriptions S
ON S.Report_OID = E.ReportID
WHERE S.subscriptionid = '3AFDAC30-4F30-423F-9F72-7C04C86026AB'
GROUP BY S.subscriptionid, S.Description, E.ReportID, S.LastStatus
Related
I have a stored procedure that returns almost 16000 rows. It also has pagination and returns 10 rows on each page.
This procedure returns user's tickets; when I use order by for sorting them, its execution speed slows down. I checked the execution plan but I don't get useful information, and just I got that order by has warning that operator used tempdb to spill data during execution with spill level 1 and 1 spilled threads, but I don't know how can I solve it.
I would like to know, how can I make my procedure execution faster?
This is my procedure:
;WITH Tickets AS
(
SELECT
t.Id ,
t.[Subject] ,
t.UserId,
t.PriorityId,
u.UserName,
c.[Name] AS UserCompanyName,
t.[Description],
t.LastStatus AS StatusId,
s.[Name] AS [Status],
t.Number AS TicketNumber,
t.CreateOn,
t.CompanyProjectId AS ProjectId ,
(SELECT TOP 1 [Name] FROM CompanyProject
WHERE CrmProjectId = t.CompanyProjectId) AS ProjectName ,
t.[TempNumber],
t.TypeRequestId AS RequestTypeId,
rt.[Name] AS RequestTypeName,
psc.NewMessagesCount,
FORMAT(DATEADD(MINUTE, t.FirstResponsePace, t.CreateOn), 'yyyy/MM/dd HH:mm', 'fa') AS FirstResponsePace,
FORMAT(DATEADD(MINUTE, t.FinishedPace, t.CreateOn), 'yyyy/MM/dd HH:mm', 'fa') AS FinishedPace,
CASE
WHEN t.SlaType IS NULL THEN N'تعیین نشده'
WHEN t.SlaType = '' THEN N'تعیین نشده'
ELSE t.SlaType
END AS SlaType
FROM
Ticket t
LEFT OUTER JOIN
dbo.AspNetUsers u ON t.UserId = u.Id
INNER JOIN
#TempSubUsers tree ON tree.UserId = u.Id
LEFT OUTER JOIN
dbo.AssignmentPosition ap ON u.Id = ap.UserId
LEFT OUTER JOIN
dbo.Company c ON c.id = ap.CompanyId
LEFT OUTER JOIN
dbo.RequestType rt ON rt.Id = t.TypeRequestId
LEFT OUTER JOIN
dbo.[Status] s ON s.Id = t.LastStatus
OUTER APPLY
(SELECT COUNT(1) AS NewMessagesCount
FROM dbo.ProcessStepComment
WHERE EntityId = t.Id AND Seen = 0 AND UserId IS NULL
GROUP BY EntityId) psc
WHERE
(t.Id = #id OR ISNULL(#id, CAST(0x0 AS UNIQUEIDENTIFIER)) = CAST(0x0 AS UNIQUEIDENTIFIER))
AND (t.CreateOn >= #sdate OR ISNULL(#sdate, '') = '')
AND (t.CreateOn <= #edate OR ISNULL(#edate, '') = '')
AND ((t.[Subject] LIKE N'%' + #generalSearch + N'%'
OR t.Number LIKE N'%' + #generalSearch + N'%'
OR t.TempNumber LIKE N'%' + #generalSearch + N'%')
OR ISNULL(#generalSearch, '') = '')
AND (t.LastStatus IN (#allStatusIdListString)
OR (SELECT COALESCE(#allStatusIdListString, CAST(0x0 AS UNIQUEIDENTIFIER))) = CAST(0x0 AS UNIQUEIDENTIFIER))
AND (t.TypeRequestId = #requestTypeId OR
ISNULL(#requestTypeId, #UniqueIdentifierDefault) = #UniqueIdentifierDefault)
AND (t.UserId = #userId OR ISNULL(#userId, '') = '')
AND (t.CompanyProjectId = #companyProject
OR ISNULL(#companyProject, #UniqueIdentifierDefault) = #UniqueIdentifierDefault)
AND (c.Id = #companyId OR ISNULL(#companyId, #UniqueIdentifierDefault) = #UniqueIdentifierDefault)
AND t.[IsEnable] = 1
)
SELECT *
FROM Tickets
ORDER BY
NewMessagesCount DESC,
CASE StatusId
WHEN 'A4E6D31F-ECD1-4288-863F-D4D5449C19D3' THEN 1
WHEN 'EB1566A1-35FD-4C8F-AC27-DB7B02D68299' THEN 2
WHEN '14F7090A-412B-4467-966F-CFEA59F7C434' THEN 3
WHEN 'E9FFB96F-2770-4763-A58D-E363D0903FB4' THEN 4
WHEN 'D002E7AA-2599-4B3C-89E6-DE8A74023E6A' THEN 5
WHEN '1A20087B-D8F1-437F-BC60-4723E5AFEB1A' THEN 6
WHEN '04BE6210-CBF9-4158-A464-7973F4FFDD6F' THEN 7
WHEN 'DF0F6E06-2AEC-4731-86DC-DF25981B852E' THEN 8
WHEN '5635F7AA-37DF-4EFF-B0C7-24E0C3BF4564' THEN 9
ELSE 10
END ASC,
CreateOn DESC
OFFSET #PageSize * (#PageNumber - 1) rows fetch next #PageSize rows ONLY
In the below query, #employee variable has larger number of characters around 57,000+ characters.
I have not included in the below query, as it will be long text.
When i lessen the values in #employee then the query works perfectly.
When values increase then i get below error.
I am getting this error -
Query processor could not produce a query plan because of the hints
defined in this query. Resubmit the query without specifying any hints
and without using SET FORCEPLAN.
DECLARE #ConfigNo NVARCHAR(100),
#month NVARCHAR(100),
#year NVARCHAR(100),
#company NVARCHAR(100),
#employee NVARCHAR(max)
SET #ConfigNo = '1'
SET #month = '10'
SET #year = '2021'
SET #company = '2'
SET #employee = '613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643'
EXEC(
'select x.Name,x.Code,x.Id,x.FieldName,x.LabelName,ISNULL(Round(y.Match,2,0),0) Match,x.Amount,x.PrintOrder,1 Flag from (select a.*,(select distinct ISNULL(value,0) from (select T.X.value(''#Value'', ''nvarchar(128)'') as Value, T.X.value(''#Name'', ''nvarchar(128)'') as ColName from dbo.TableTran cross apply TransactionFieldDetails.nodes(''/PayDetails/Column'') as T(X) where EmployeeId = a.Id and MONTH = '
+#month+' and year = '+#year+
') abc where ColName = a.FieldName) Amount from ( select s.FieldName,s.LabelName,isnull(e.FName,'''') + '' '' + isnull(e.LName,'''') as Name,e.Code,e.Id,s.PrintOrder from dbo.TablePrint s cross join dbo.TableDetail e where ComponentType = 1 and e.Id in ('
+#employee+') and s.PayConNo = '+#ConfigNo+' and s.CompanyId = '+#company+
') a ) x left join ( select a.*, (select distinct ISNULL(value,0) from (select T.X.value(''#Value'', ''nvarchar(128)'') as Value, T.X.value(''#Name'', ''nvarchar(128)'') as ColName from dbo.TableTran cross apply TransactionFieldDetails.nodes(''/PayDetails/Column'') as T(X) where EmployeeId = a.Id and MONTH = '
+#month+' and year = '+#year+
') abc where ColName = a.ComputeField) Match from ( select s.ActualField, s.ComputeField,e.FName,e.Id from dbo.PaySlipMatching s cross join dbo.TableDetail e where e.Id in ('
+#employee+') and s.PayConNo = '+#ConfigNo+' and s.CompanyId = '+#company+
') a ) y on x.FieldName = y.ActualField and x.Id = y.Id union all select a.Name,a.Code,a.id,a.FieldName,a.LabelName,0 Match, (select distinct ISNULL(value,0) from (select T.X.value(''#Value'', ''nvarchar(128)'') as Value, T.X.value(''#Name'', ''nvarchar(128)'') as ColName from dbo.TableTran cross apply TransactionFieldDetails.nodes(''/PayDetails/Column'') as T(X) where EmployeeId = a.Id and MONTH = '
+#month+' and year = '+#year+
') abc where ColName = a.FieldName) Amount,a.PrintOrder, 0 Flag from ( select s.FieldName,s.LabelName,isnull(e.FName,'''') + '' '' + isnull(e.LName,'''') as Name,e.Code,e.Id,s.PrintOrder from dbo.TablePrint s cross join dbo.TableDetail e where ComponentType = 2 and e.Id in ('
+#employee+') and s.PayConNo = '+#ConfigNo+' and s.CompanyId = '+#company+
' ) a OPTION (FORCE ORDER)')
Please help me out with any solution or idea.
Formatted Query -
SELECT x.NAME,
x.code,
x.id,
x.fieldname,
x.labelname,
Isnull(Round(y.match, 2, 0), 0) Match,
x.amount,
x.printorder,
1 Flag
FROM (SELECT a.*,
(SELECT DISTINCT Isnull(value, 0)
FROM (SELECT t.x.value('#Value', 'nvarchar(128)') AS Value,
t.x.value('#Name', 'nvarchar(128)') AS ColName
FROM dbo.tabletrans
CROSS apply
transactionfielddetails.nodes('/PayDetails/Column')
AS T(x)
WHERE employeeid = a.id
AND month = 10
AND year = 2021) abc
WHERE colname = a.fieldname) Amount
FROM (SELECT s.fieldname,
s.labelname,
Isnull(e.fname, '') + ' ' + Isnull(e.lname, '') AS NAME,
e.code,
e.id,
s.printorder
FROM dbo.tableprint s
CROSS JOIN dbo.tabledetail e
WHERE componenttype = 1
AND e.id IN ( 25039, 25040, 25041, 25042,
25043, 25044, 25045, 25452 )
AND s.payconno = 1
AND s.companyid = 2) a) x
LEFT JOIN (SELECT a.*,
(SELECT DISTINCT Isnull(value, 0)
FROM (SELECT t.x.value('#Value', 'nvarchar(128)') AS Value,
t.x.value('#Name', 'nvarchar(128)') AS
ColName
FROM dbo.tabletrans
CROSS apply
transactionfielddetails.nodes('/PayDetails/Column')
AS T(x)
WHERE employeeid = a.id
AND month = 10
AND year = 2021) abc
WHERE colname = a.computefield) Match
FROM (SELECT s.actualfield,
s.computefield,
e.fname,
e.id
FROM dbo.payslipmatching s
CROSS JOIN dbo.tabledetail e
WHERE e.id IN ( 25039, 25040, 25041, 25042,
25043, 25044, 25045, 25452 )
AND s.payconno = 1
AND s.companyid = 2) a) y
ON x.fieldname = y.actualfield
AND x.id = y.id
UNION ALL
SELECT a.NAME,
a.code,
a.id,
a.fieldname,
a.labelname,
0 Match,
(SELECT DISTINCT Isnull(value, 0)
FROM (SELECT t.x.value('#Value', 'nvarchar(128)') AS Value,
t.x.value('#Name', 'nvarchar(128)') AS ColName
FROM dbo.tabletrans
CROSS apply
transactionfielddetails.nodes('/PayDetails/Column')
AS T(x)
WHERE employeeid = a.id
AND month = 10
AND year = 2021) abc
WHERE colname = a.fieldname) Amount,
a.printorder,
0 Flag
FROM (SELECT s.fieldname,
s.labelname,
Isnull(e.fname, '') + ' ' + Isnull(e.lname, '') AS NAME,
e.code,
e.id,
s.printorder
FROM dbo.tableprint s
CROSS JOIN dbo.tabledetail e
WHERE componenttype = 2
AND e.id IN ( 25039, 25040, 25041, 25042,
25043, 25044, 25045, 25452 )
AND s.payconno = 1
AND s.companyid = 2) a
OPTION (force ORDER)
This is my sample code:
SQL Fiddle
I need it to result like this:
category outlet1 outlet2 outlet3
Sale 70 20 40
Expense 250 130 200
How can I do this?
EDIT: My outlets are not fixed, sorry for not telling this beforehand.
You can solve your particular problem using conditional aggregation:
SELECT c.category,
SUM(CASE WHEN o.outletname = 'Outlet1' THEN t.amt ELSE 0 END) as Outlet1,
SUM(CASE WHEN o.outletname = 'Outlet2' THEN t.amt ELSE 0 END) as Outlet2,
SUM(CASE WHEN o.outletname = 'Outlet3' THEN t.amt ELSE 0 END) as Outlet3
FROM tblcategory c INNER JOIN
tbltran t
ON t.catid = c.id INNER JOIN
tbloutlet o
ON o.id = t.outletid
GROUP BY c.category;
If the outlet names are not fixed, then you need dynamic SQL. The problem cannot be solve using a single SELECT query.
Here with dynamic Outlets http://sqlfiddle.com/#!18/a7b09/25
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(outletname)
from tbloutlet
group by outletname
order by outletname
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT category,' + #cols + ' from
(
SELECT c.category, o.outletname, SUM(t.amt) as amt
FROM tblcategory c
INNER JOIN tbltran t ON t.catid = c.id
INNER JOIN tbloutlet o ON o.id = t.outletid
GROUP BY c.category, o.outletname
) x
pivot
(
sum(amt)
for outletname in (' + #cols + ')
) p '
execute(#query);
you may also use the PIVOT operator
SELECT *
FROM
(
SELECT category, outletname, amt
FROM tblcategory c
INNER JOIN tbltran t ON t.catid = c.id
INNER JOIN tbloutlet o ON o.id = t.outletid
) d
PIVOT
(
SUM(amt)
FOR outletname in ([Outlet1] , [Outlet2] , [Outlet3])
) p
EDIT : below is the Dynamic SQL version
declare #Outlets nvarchar(max),
#SQL nvarchar(max)
select #Outlets = isnull(#Outlets + ',', '') + quotename(outlet)
from outlet
select #SQL = '
SELECT *
FROM
(
SELECT category, outletname, amt
FROM tblcategory c
INNER JOIN tbltran t ON t.catid = c.id
INNER JOIN tbloutlet o ON o.id = t.outletid
) d
PIVOT
(
SUM(amt)
FOR outletname in (' + #Outlets + ')
) p'
print #SQL -- print out for verification
exec sp_executesql #SQL
I wrote a stored procedure to search the users in my database. But sometimes it returns too many users, and it takes too much time.
So if the result set has over 500 rows, I decided to return only the first 500 rows. But I have no idea how to get count from stored procedure.
Please help me.
My original stored procedure is below. Thanks
ALTER PROCEDURE [dbo].[up_Select_SearchUser]
#companyCode varchar(50)
, #keyword nvarchar(20)
, #isRelative bit
, #langCode varchar(10)
AS
BEGIN
SET NOCOUNT ON;
SELECT
LOWER(M.UserID) AS EmpID,
LOWER(M.EmpID) AS REmpID,
dbo.uf_CompanyPhone(M.CompanyPhone, M.ExtensionNumber) AS ExtensionNumber,
M.CellPhone,
dbo.uf_TeamManagerYN(M.UserID) AS TeamChiefYN,
ISNULL(M.DisplayName, '') AS DisplayName,
ISNULL(M.DisplayName_Eng, '') AS DisplayName_Eng,
M.EMail,
M.MainDeptCode AS DeptCode,
ISNULL(DT.DisplayName, '') AS DeptName,
ISNULL(CL.CompanyCode, '') AS CompanyCode,
ISNULL(CL.CompanyName, '') AS CompanyName,
ISNULL(R.RankCode, '') AS RankCode,
ISNULL(R.RankName, '') AS RankName,
ISNULL(J.JobCode, '') AS JobCode,
ISNULL(J.JobName, '') AS JobName,
ISNULL(D.DutyCode, '') AS DutyCode,
ISNULL(D.DutyName, '') AS DutyName,
ISNULL(M.FaxNumber, '') AS FaxNumber,
ISNULL(M.ADDisplayName, '') AS ADDisplayName,
'' AS Address,
ISNULL(M.CompanyPhone, '') AS CompanyPhone,
ISNULL(R.SortOrder, '') AS RankOrder
FROM
dbo.tb_User M WITH (NOLOCK)
INNER JOIN
dbo.tb_Dept DT WITH (NOLOCK) ON M.MainDeptCode = DT.DeptCode
INNER JOIN
dbo.tb_Rank R WITH (NOLOCK) ON M.RankCode = R.RankCode
AND M.GroupCode = R.GroupCode
AND M.DetailCode = R.DetailCode
AND M.CompanyCode = R.CompanyCode
INNER JOIN
dbo.tb_Company CL WITH (NOLOCK) ON M.CompanyCode = CL.CompanyCode
LEFT OUTER JOIN
dbo.tb_Duty D WITH (NOLOCK) ON M.DutyCode = D.DutyCode
AND M.GroupCode = D.GroupCode
AND M.DetailCode = D.DetailCode
AND M.CompanyCode = D.CompanyCode
LEFT OUTER JOIN
dbo.tb_Job J WITH (NOLOCK) ON M.JobCode = J.JobCode
WHERE
(M.DisplayName LIKE '%' + #keyword + '%'
OR M.UserID LIKE '%' + #keyword + '%')
AND M.DisplayYN = 'Y'
AND M.CompanyCode LIKE #companyCode
ORDER BY
RankOrder, JobCode, DisplayName
END
Add TOP 500 to the select query. This will make sure that the result count will not be more than 500. If it's less than 500 it will take the number of records.If it's greater than 500, it will filter the top 500 records.
ALTER PROCEDURE [dbo].[up_Select_SearchUser]
#companyCode varchar(50)
, #keyword nvarchar(20)
, #isRelative bit
, #langCode varchar(10)
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP 500 LOWER(M.UserID) AS EmpID
, LOWER(M.EmpID) AS REmpID
, dbo.uf_CompanyPhone(M.CompanyPhone, M.ExtensionNumber) AS ExtensionNumber
, M.CellPhone
, dbo.uf_TeamManagerYN(M.UserID) AS TeamChiefYN
, ISNULL(M.DisplayName,'') AS DisplayName
, ISNULL(M.DisplayName_Eng,'') AS DisplayName_Eng
, M.EMail
, M.MainDeptCode AS DeptCode
, ISNULL(DT.DisplayName,'') AS DeptName
, ISNULL(CL.CompanyCode,'') AS CompanyCode
, ISNULL(CL.CompanyName,'') AS CompanyName
, ISNULL(R.RankCode,'') AS RankCode
, ISNULL(R.RankName,'') AS RankName
, ISNULL(J.JobCode,'') AS JobCode
, ISNULL(J.JobName,'') AS JobName
, ISNULL(D.DutyCode,'') AS DutyCode
, ISNULL(D.DutyName,'') AS DutyName
, ISNULL(M.FaxNumber,'') AS FaxNumber
, ISNULL(M.ADDisplayName,'') AS ADDisplayName
, '' AS Address
, ISNULL(M.CompanyPhone, '') AS CompanyPhone
, ISNULL(R.SortOrder,'') AS RankOrder
FROM dbo.tb_User M WITH (NOLOCK)
INNER JOIN dbo.tb_Dept DT WITH (NOLOCK)
ON M.MainDeptCode = DT.DeptCode
INNER JOIN dbo.tb_Rank R WITH (NOLOCK)
ON M.RankCode = R.RankCode
AND M.GroupCode = R.GroupCode
AND M.DetailCode = R.DetailCode
AND M.CompanyCode = R.CompanyCode
INNER JOIN dbo.tb_Company CL WITH (NOLOCK)
ON M.CompanyCode = CL.CompanyCode
LEFT OUTER JOIN dbo.tb_Duty D WITH (NOLOCK)
ON M.DutyCode = D.DutyCode
AND M.GroupCode = D.GroupCode
AND M.DetailCode = D.DetailCode
AND M.CompanyCode = D.CompanyCode
LEFT OUTER JOIN dbo.tb_Job J WITH (NOLOCK)
ON M.JobCode = J.JobCode
WHERE (M.DisplayName LIKE '%' + #keyword + '%'
OR M.UserID LIKE '%' + #keyword + '%')
AND M.DisplayYN = 'Y'
AND M.CompanyCode LIKE #companyCode
ORDER BY RankOrder , JobCode, DisplayName
Use this statement instead of SELECT TOP:
SELECT * FROM Products
WHERE id BETWEEN 10 AND 20;
for a better control
for a better example wiev:
Equivalent of LIMIT and OFFSET for SQL Server?
As i understand from your question is you wants to select only 500 or 100 records its upto u how many records u wants to select simply u can use
select top 500 [lisofyourcolums] from your table;
if u want do a paging u can simply do changes in your Stored procedure like below
ALTER PROCEDURE [dbo].[up_Select_SearchUser]
#companyCode varchar(50)
, #keyword nvarchar(20)
, #isRelative bit
, #langCode varchar(10)
, #startRowIndex int=1
, #maximumRows int=500
AS
BEGIN
SET NOCOUNT ON;
DECLARE #startRow int,#totalRows int
SET #startRowIndex = (#startRowIndex - 1) * #maximumRows
Print #startRowIndex
IF #startRowIndex = 0
SET #startRowIndex = 1
Else
SET #startRowIndex = #startRowIndex+1
Print #startRowIndex
SET ROWCOUNT #startRowIndex
select [yourcolumnList] from yourtable
SET ROWCOUNT #maximumRows
SELECT
END
I hope this will help u...
Select #Count = COUNT()
From Table
Where <Your Condition>
Then use IF statement:
if #Count > 500 then
SELECT TOP 500
LOWER(M.UserID) = AS EmpID
Try this
ALTER PROCEDURE [dbo].[up_Select_SearchUser]
#companyCode varchar(50)
, #keyword nvarchar(20)
, #isRelative bit
, #langCode varchar(10)
, #PageNumber INT = 1--Give Page number you required
, #PageSize INT = 100 --Give number of rows you required per Page
AS
BEGIN
SET NOCOUNT ON;
SELECT LOWER(M.UserID) AS EmpID
, LOWER(M.EmpID) AS REmpID
, dbo.uf_CompanyPhone(M.CompanyPhone, M.ExtensionNumber) AS ExtensionNumber
, M.CellPhone
, dbo.uf_TeamManagerYN(M.UserID) AS TeamChiefYN
, ISNULL(M.DisplayName,'') AS DisplayName
, ISNULL(M.DisplayName_Eng,'') AS DisplayName_Eng
, M.EMail
, M.MainDeptCode AS DeptCode
, ISNULL(DT.DisplayName,'') AS DeptName
, ISNULL(CL.CompanyCode,'') AS CompanyCode
, ISNULL(CL.CompanyName,'') AS CompanyName
, ISNULL(R.RankCode,'') AS RankCode
, ISNULL(R.RankName,'') AS RankName
, ISNULL(J.JobCode,'') AS JobCode
, ISNULL(J.JobName,'') AS JobName
, ISNULL(D.DutyCode,'') AS DutyCode
, ISNULL(D.DutyName,'') AS DutyName
, ISNULL(M.FaxNumber,'') AS FaxNumber
, ISNULL(M.ADDisplayName,'') AS ADDisplayName
, '' AS Address
, ISNULL(M.CompanyPhone, '') AS CompanyPhone
, ISNULL(R.SortOrder,'') AS RankOrder
FROM dbo.tb_User M WITH (NOLOCK)
INNER JOIN dbo.tb_Dept DT WITH (NOLOCK)
ON M.MainDeptCode = DT.DeptCode
INNER JOIN dbo.tb_Rank R WITH (NOLOCK)
ON M.RankCode = R.RankCode
AND M.GroupCode = R.GroupCode
AND M.DetailCode = R.DetailCode
AND M.CompanyCode = R.CompanyCode
INNER JOIN dbo.tb_Company CL WITH (NOLOCK)
ON M.CompanyCode = CL.CompanyCode
LEFT OUTER JOIN dbo.tb_Duty D WITH (NOLOCK)
ON M.DutyCode = D.DutyCode
AND M.GroupCode = D.GroupCode
AND M.DetailCode = D.DetailCode
AND M.CompanyCode = D.CompanyCode
LEFT OUTER JOIN dbo.tb_Job J WITH (NOLOCK)
ON M.JobCode = J.JobCode
WHERE (M.DisplayName LIKE '%' + #keyword + '%'
OR M.UserID LIKE '%' + #keyword + '%')
AND M.DisplayYN = 'Y'
AND M.CompanyCode LIKE #companyCode
ORDER BY RankOrder , JobCode, DisplayName
OFFSET #PageSize * (#PageNumber - 1) ROWS
FETCH NEXT #PageSize ROWS ONLY
END
Declare one variable to get input from user to show how many records he wants to return
ALTER PROCEDURE [dbo].[up_Select_SearchUser]
#companyCode varchar(50)
, #keyword nvarchar(20)
, #isRelative bit
, #langCode varchar(10)
, #NumberOfRows INT
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP #NumberOfRows
LOWER(M.UserID) AS EmpID,
LOWER(M.EmpID) AS REmpID,
dbo.uf_CompanyPhone(M.CompanyPhone, M.ExtensionNumber) AS ExtensionNumber,
M.CellPhone,
dbo.uf_TeamManagerYN(M.UserID) AS TeamChiefYN,
ISNULL(M.DisplayName, '') AS DisplayName,
ISNULL(M.DisplayName_Eng, '') AS DisplayName_Eng,
M.EMail,
M.MainDeptCode AS DeptCode,
ISNULL(DT.DisplayName, '') AS DeptName,
ISNULL(CL.CompanyCode, '') AS CompanyCode,
ISNULL(CL.CompanyName, '') AS CompanyName,
ISNULL(R.RankCode, '') AS RankCode,
ISNULL(R.RankName, '') AS RankName,
ISNULL(J.JobCode, '') AS JobCode,
ISNULL(J.JobName, '') AS JobName,
ISNULL(D.DutyCode, '') AS DutyCode,
ISNULL(D.DutyName, '') AS DutyName,
ISNULL(M.FaxNumber, '') AS FaxNumber,
ISNULL(M.ADDisplayName, '') AS ADDisplayName,
'' AS Address,
ISNULL(M.CompanyPhone, '') AS CompanyPhone,
ISNULL(R.SortOrder, '') AS RankOrder
FROM
dbo.tb_User M WITH (NOLOCK)
INNER JOIN
dbo.tb_Dept DT WITH (NOLOCK) ON M.MainDeptCode = DT.DeptCode
INNER JOIN
dbo.tb_Rank R WITH (NOLOCK) ON M.RankCode = R.RankCode
AND M.GroupCode = R.GroupCode
AND M.DetailCode = R.DetailCode
AND M.CompanyCode = R.CompanyCode
INNER JOIN
dbo.tb_Company CL WITH (NOLOCK) ON M.CompanyCode = CL.CompanyCode
LEFT OUTER JOIN
dbo.tb_Duty D WITH (NOLOCK) ON M.DutyCode = D.DutyCode
AND M.GroupCode = D.GroupCode
AND M.DetailCode = D.DetailCode
AND M.CompanyCode = D.CompanyCode
LEFT OUTER JOIN
dbo.tb_Job J WITH (NOLOCK) ON M.JobCode = J.JobCode
WHERE
(M.DisplayName LIKE '%' + #keyword + '%'
OR M.UserID LIKE '%' + #keyword + '%')
AND M.DisplayYN = 'Y'
AND M.CompanyCode LIKE #companyCode
ORDER BY
RankOrder, JobCode, DisplayName
END
I have a stored procedure whose data looks like below
Now what I want is, I want to insert its data into two different temp table
First temp table will have these columns
Doc_type, Doc_No, No_of_days
Second temp table will have columns
Username, DocType, No_of_days
I tried like this:
CREATE TABLE #table1
(
Doc_type varchar(55),
Doc_No varchar(55),
No_of_days varchar(55),
)
INSERT INTO #table1
But it throws an error:
Incorrect syntax near the keyword 'END'.
Here is my complete stored procedure:
Alter procedure GET_INWARD_REMINDER_REPORT
AS
BEGIN
Select
U.first_name + ' ' + U.last_name UserName,
TH.User_ID,
TY.Type_desc Document_Type,
RA.mkey Reporting_To,
U.Email AS UserEmail,
RAU.Email AS RA1_Email,
RAU.first_name + ' ' + RAU.last_name RAName,
TH.Doc_No,
DATEDIFF(DAY, TH.LastAction_DateTime, GETDATE()) - DATEDIFF(WK, TH.LastAction_DateTime, GETDATE()) AS No_Of_Days_Doc_Pending
from
inward_doc_tracking_hdr TH
inner join
user_mst U ON TH.User_Id = U.mkey
inner join
emp_mst M ON M.mkey = U.employee_mkey
inner join
type_mst_a TY ON TY.master_mkey = TH.doc_type
inner join
emp_mst RA ON RA.mkey = M.Reporting_To
inner join
user_mst RAU ON RAU.employee_mkey = RA.mkey
where
TH.Status_flag NOT IN (5,14) --- 5 for close, 14 for return
and TH.To_user IS NOT NULL
CREATE TABLE #table1
(
Doc_type varchar(55),
Doc_No varchar(55),
No_of_days varchar(55),
)
INSERT INTO #table1
Get all data to temp table then insert.
INSERT INTO #MainTemp
EXEC [GET_INWARD_REMINDER_REPORT];
INSERT INTO #table1
select Doc_type, Doc_No, No_of_days from #MainTemp
INSERT INTO #table2
select Username, DocType, No_of_days from #MainTemp
UPDATED
You can use MainTempTable.
Alter procedure GET_INWARD_REMINDER_REPORT
AS
BEGIN
IF EXISTS(SELECT * FROM dbo.MainTempTable)
DROP TABLE dbo.MainTempTable
Select
U.first_name + ' ' + U.last_name UserName,
TH.User_ID,
TY.Type_desc Document_Type,
RA.mkey Reporting_To,
U.Email AS UserEmail,
RAU.Email AS RA1_Email,
RAU.first_name + ' ' + RAU.last_name RAName,
TH.Doc_No,
DATEDIFF(DAY,TH.LastAction_DateTime,GETDATE()) - DATEDIFF(WK,TH.LastAction_DateTime, GETDATE())
AS No_Of_Days_Doc_Pending
INTO MainTempTable
from inward_doc_tracking_hdr TH
inner join
user_mst U ON TH.User_Id = U.mkey
inner join
emp_mst M ON M.mkey = U.employee_mkey
inner join
type_mst_a TY ON TY.master_mkey = TH.doc_type
inner join
emp_mst RA ON RA.mkey = M.Reporting_To
inner join
user_mst RAU ON RAU.employee_mkey = RA.mkey
where
TH.Status_flag NOT IN (5,14) --- 5 for close, 14 for return
and TH.To_user IS NOT NULL
SELECT
userName,
COUNT(Doc_No) CountofDocNo
FROM
MainTempTable
GROUP BY
userName
END