SSRS Subscriptions - How to view ALL report recipients - reporting-services

I've written an SSRS report to help me keep track of SSRS subscriptions. I've repurposed a script that will use Reportserver.dbo.Subscriptions.LastStatus to view email recipients, however, it will only list the first 520 characters of LastStatus. Because some of our distribution lists are quite large, some of the names that my script searches for are not being found (even though they are part of the distribution). Below is the script that I am using:
SELECT Reportname = c.Name
,FileLocation = c.Path
,SubscriptionDesc=su.Description
,Subscriptiontype=su.EventType
,su.LastStatus
,su.LastRunTime
,Schedulename=sch.Name
,ScheduleType = sch.EventType
,ScheduleFrequency =
CASE sch.RecurrenceType
WHEN 1 THEN 'Once'
WHEN 2 THEN 'Hourly'
WHEN 4 THEN 'Daily/Weekly'
WHEN 5 THEN 'Monthly'
END
,su.Parameters
FROM Reportserver.dbo.Subscriptions su
JOIN Reportserver.dbo.Catalog c
ON su.Report_OID = c.ItemID
JOIN Reportserver.dbo.ReportSchedule rsc
ON rsc.ReportID = c.ItemID
AND rsc.SubscriptionID = su.SubscriptionID
JOIN Reportserver.dbo.Schedule Sch
ON rsc.ScheduleID = sch.ScheduleID
WHERE LastStatus like #Email
ORDER BY LastRunTime DESC
Any code that I have found online uses the LastStatus column to display this data. If anyone has any suggestions as to a more complete way for me to list all of the members of the report distribution list, I would appreciate it.

Below is SQL to query for the full text of the subscription parameters. I think this will work with extremely long address lists, but I don't have a test server with long address lists available right now.
If using this in production, I'd probably throw in a couple of WITH ( NOLOCK )'s and wouldn't expect support from MS on problems.
;
WITH subscriptionXmL
AS (
SELECT
SubscriptionID ,
OwnerID ,
Report_OID ,
Locale ,
InactiveFlags ,
ExtensionSettings ,
CONVERT(XML, ExtensionSettings) AS ExtensionSettingsXML ,
ModifiedByID ,
ModifiedDate ,
Description ,
LastStatus ,
EventType ,
MatchData ,
LastRunTime ,
Parameters ,
DeliveryExtension ,
Version
FROM
ReportServer.dbo.Subscriptions
),
-- Get the settings as pairs
SettingsCTE
AS (
SELECT
SubscriptionID ,
ExtensionSettings ,
-- include other fields if you need them.
ISNULL(Settings.value('(./*:Name/text())[1]', 'nvarchar(1024)'),
'Value') AS SettingName ,
Settings.value('(./*:Value/text())[1]', 'nvarchar(max)') AS SettingValue
FROM
subscriptionXmL
CROSS APPLY subscriptionXmL.ExtensionSettingsXML.nodes('//*:ParameterValue') Queries ( Settings )
)
SELECT
*
FROM
SettingsCTE
WHERE
settingName IN ( 'TO', 'CC', 'BCC' )

I also found this query from SQL Server MSDN Social;
Original Query Author MSDN Profile: Sandip Shinde
SELECT
c.Name AS ReportName,
'Next Run Date' = CASE next_run_date
WHEN 0 THEN null
ELSE
substring(convert(varchar(15),next_run_date),1,4) + '/' +
substring(convert(varchar(15),next_run_date),5,2) + '/' +
substring(convert(varchar(15),next_run_date),7,2)
END,
'Next Run Time' = isnull(CASE len(next_run_time)
WHEN 3 THEN cast('00:0'
+ Left(right(next_run_time,3),1)
+':' + right(next_run_time,2) as char (8))
WHEN 4 THEN cast('00:'
+ Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
WHEN 5 THEN cast('0' + Left(right(next_run_time,5),1)
+':' + Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
WHEN 6 THEN cast(Left(right(next_run_time,6),2)
+':' + Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
END,'NA'),
Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="TO"])[1]','nvarchar(50)') as [To]
,Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="CC"])[1]','nvarchar(50)') as [CC]
,Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="RenderFormat"])[1]','nvarchar(50)') as [Render Format]
,Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="Subject"])[1]','nvarchar(50)') as [Subject]
---Example report parameters: StartDateMacro, EndDateMacro & Currency.
,Convert(XML,[Parameters]).value('(//ParameterValue/Value[../Name="StartDateMacro"])[1]','nvarchar(50)') as [Start Date]
,Convert(XML,[Parameters]).value('(//ParameterValue/Value[../Name="EndDateMacro"])[1]','nvarchar(50)') as [End Date]
,Convert(XML,[Parameters]).value('(//ParameterValue/Value[../Name="Currency"])[1]','nvarchar(50)') as [Currency]
,[LastStatus]
,[EventType]
,[LastRunTime]
,[DeliveryExtension]
,[Version]
FROM
dbo.[Catalog] c
INNER JOIN dbo.[Subscriptions] S ON c.ItemID = S.Report_OID
INNER JOIN dbo.ReportSchedule R ON S.SubscriptionID = R.SubscriptionID
INNER JOIN msdb.dbo.sysjobs J ON Convert(nvarchar(128),R.ScheduleID) = J.name
INNER JOIN msdb.dbo.sysjobschedules JS ON J.job_id = JS.job_id

According to MS (https://learn.microsoft.com/en-us/sql/reporting-services/subscriptions/manage-subscription-owners-and-run-subscription-powershell?view=sql-server-ver16), you can also use this powershell command:
$webSRV = New-WebServiceProxy -Uri "http://myservername/ReportServer/ReportService2010.asmx" -Namespace SSRS.ReportingService2010 -UseDefaultCredential;
$mySubsList = $webSRV.ListSubscriptions("/");
$mySubsList | select *

Related

complex query - look back on same table data to output results in mysql (VERY slow query)

I'm trying to optimize a query, which as the db is growing, its performance is severely lacking.
Background: we are trying to find a list of users who have taken a course and their credential is now due to be renewed (or has not renewed). In searching the query we have to have a look into the registration table (which is the same table that holds all their registration history) and find records where they have not renewed. (Each time the client takes a course they have a registration record added.) The query I'm wanting to optimize looks to see if they've (client) taken the same course type on a date/time after the last class (of same type) they took. If there is no record it should result row(s) that they didn't renew their course. it sounds easy, but, as you know, when you're in the heat of writing a query it gets very complex--and even more so once the db has grown to be so large that it takes almost 5-6 minutes to find the data. So, I'm asking for help on how I can optimize the efforts of my predecessor, below.
Here is the query, thus far (don't laugh, it wasn't started by me--I took over the project).
I have no clue where to begin with optimizing this MySQL. I think it needs to have select statements within the JOINS, but I'm at your mercy to direct me as to where to start! (I"m not a db guy, but offered to take a look and see where we can fix this).
Thanks a million for reading.
Lee
SELECT
r.GUID AS `A/C #`,
concat( a.AttendeeLastName, ', ', a.AttendeeFirstName ) AS Full Name (Last, First),
r.CourseExpirationDateFull AS `Exp Date`,
mtype_master_abbrev AS Course,
a.EmailName AS Email,
r.EventID,
r.EventTypeMasterID,
m.type_master_name,
IF( ( r.CourseExpirationDateFull < curdate( ) ), 'Expired', 'Valid' ) AS Status,
e.StartDateTime,
( to_days( curdate( ) ) - to_days( r.ExpNoticeSent ) ) AS Last Notice,
r.AttendeeID,
a.AttendeeCredentials,
r.RegistrationID,
r.RenewedExternalYYYY,
r.ExpNoticeSent,
q.RenewedRegID,
rs.reg_status_name AS `Reg Status`,
( to_days( r.CourseExpirationDateFull ) - to_days( curdate( ) ) ) AS Days2Exp,
a.flgReturnEmail,
a.flgSendEmail,
r.reg_type_ID,
a._usr_flg_do_not_call,
a.flgPrintLetter
e.EventTypeMasterID AS MasterID,
c.Last: yy-mm-dd - by - topic AS LastComm,
r.reg_renewal_status_id
FROM
vjgzuqrr_wtsql.registration r LEFT JOIN vjgzuqrr_wtsql.events ON ( r.EventID = events.EventID ) LEFT JOIN
vjgzuqrr_wtsql.attendees a ON a.ID = r.GUID LEFT JOIN
vjgzuqrr_wtsql.tbl_crs_type_master m ON r.EventTypeMasterID = m.ID_crs_type_master LEFT JOIN
vjgzuqrr_wtsql.qryrenreg q ON r.RegistrationID = q.OrigRegID LEFT JOIN
vjgzuqrr_wtsql.tbl_reg_status rs ON rs.ID_reg_status = r.RegistrationStatus LEFT JOIN
vjgzuqrr_wtsql.v_last_contact c ON c.registrationid = r.RegistrationID
WHERE
r.Role = 1
AND r.reg_type_ID IN ( 1, 2 )
AND r.CompletionStatus IN ( 9, 8 )
AND r.r IN ( 1, 14, 9 )
AND ( r.EventTypeMasterID IS NOT NULL OR r.EventTypeMasterID = 17 )
AND r.flgDelete = 0
AND r.flgTest = 0
AND e.flgDelete = 0
AND e.flgTestCourse = 0
AND e.flgDelete = 0
AND a.flgTest = 0
AND isnull( q.RenewedRegID )
AND a.flgReturnEmail = 0
AND m.type_master_abbrev NOT IN ( 'EKGPHARM', 'IVCERT', 'sem', 'fam&friends', 'cccc' )
Edit to include Explain:
Sorry im a bit slow, mysql,
This does not speed anything up ( i think, but it may help a bit), but it should help in reading it in a non-mindbreaking way. (hopefully this will also help others look at it.)
SELECT
r.GUID AS `A/C #`,
concat( a.AttendeeLastName, ', ', a.AttendeeFirstName ) AS Full Name (Last, First),
r.CourseExpirationDateFull AS `Exp Date`,
mtype_master_abbrev AS Course,
a.EmailName AS Email,
r.EventID,
r.EventTypeMasterID,
m.type_master_name,
IF( ( r.CourseExpirationDateFull < curdate( ) ), 'Expired', 'Valid' ) AS Status,
e.StartDateTime,
( to_days( curdate( ) ) - to_days( r.ExpNoticeSent ) ) AS Last Notice,
r.AttendeeID,
a.AttendeeCredentials,
r.RegistrationID,
r.RenewedExternalYYYY,
r.ExpNoticeSent,
q.RenewedRegID,
rs.reg_status_name AS `Reg Status`,
( to_days( r.CourseExpirationDateFull ) - to_days( curdate( ) ) ) AS Days2Exp,
a.flgReturnEmail,
a.flgSendEmail,
r.reg_type_ID,
a._usr_flg_do_not_call,
a.flgPrintLetter
e.EventTypeMasterID AS MasterID,
c.Last: yy-mm-dd - by - topic AS LastComm,
r.reg_renewal_status_id
FROM
vjgzuqrr_wtsql.registration r LEFT JOIN
vjgzuqrr_wtsql.events e ON r.EventID = e.EventID LEFT JOIN
vjgzuqrr_wtsql.attendees a ON a.ID = r.GUID LEFT JOIN
vjgzuqrr_wtsql.tbl_crs_type_master m ON r.EventTypeMasterID = m.ID_crs_type_master LEFT JOIN
vjgzuqrr_wtsql.qryrenreg q ON r.RegistrationID = q.OrigRegID LEFT JOIN
vjgzuqrr_wtsql.tbl_reg_status rs ON rs.ID_reg_status = r.RegistrationStatus LEFT JOIN
vjgzuqrr_wtsql.v_last_contact c ON c.registrationid = r.RegistrationID
WHERE
r.Role = 1
AND r.reg_type_ID IN ( 1, 2 )
AND r.CompletionStatus IN ( 9, 8 )
AND r.r IN ( 1, 14, 9 )
AND ( r.EventTypeMasterID IS NOT NULL OR r.EventTypeMasterID = 17 )
AND r.flgDelete = 0
AND r.flgTest = 0
AND e.flgDelete = 0
AND e.flgTestCourse = 0
AND e.flgDelete = 0
AND a.flgTest = 0
AND isnull( q.RenewedRegID )
AND a.flgReturnEmail = 0
AND m.type_master_abbrev NOT IN ( 'EKGPHARM', 'IVCERT', 'sem', 'fam&friends', 'cccc' )

Distinct in concatenated columns from a table in ms sql

I run this query in my db the results are not distinct. Is there any solution to get the distinct results while using concatenation in select clause.
select
case
when c.SubtypeId_FK is null then c.TypeDescription
else c.TypeDescription + ' In ' + cs.Subtype
end as Experties
from
CaseTLS c,
CaseLawyer cl ,
Lawyer l ,
CaseSubtype cs
where
c.CaseId = cl.CaseID
and cl.ComputerCode = l.ComputerCode
and l.ComputerCode = #p1
and (
c.SubtypeId_FK = cs.SubtypeId or c.SubtypeId_FK is null
)
Simply use Distinct in select clause.
Try this:
select
DISTINCT case
when c.SubtypeId_FK is null then c.TypeDescription
else c.TypeDescription + ' In ' + cs.Subtype
end as Experties
from
CaseTLS c,
CaseLawyer cl ,
Lawyer l ,
CaseSubtype cs
where
c.CaseId = cl.CaseID
and cl.ComputerCode = l.ComputerCode
and l.ComputerCode = #p1
and (
c.SubtypeId_FK = cs.SubtypeId or c.SubtypeId_FK is null
)

How to do a proper SQL recursion?

I'm currently working on a little error-handling issue in the following query:
declare #DayCounter int
declare #rows int
set #DayCounter = -2
set #rows = 0
while #rows = 0
begin
select
coalesce(p.name, case when len(ol.action)>1 then substring(ol.action,1,40)+'<br />'+substring(ol.action,41,80) else ca.code end) as description
, convert(varchar,DateAdd(minute,
15 * ((60 * Datepart(hour, latest_payment_status_change) +
Datepart(Minute, latest_payment_status_change)+
Case When DatePart(second, latest_payment_status_change) < 30
Then 7 Else 8 End) / 15),
DateAdd(day, DateDiff(day, 0, latest_payment_status_change), 0)),126) as date_time
, sum(num_of_persons) as num_tickets
from tick_order o
join tick_orderline ol on ol.order_id=o.id
join (
select olt.id
from tick_orderline_type olt
join tick_case ca on ca.id=olt.case_id
join tick_client tcl on tcl.id = ca.client_id
where tcl.id = 'CLIENT_TEST'
union
select orderline_type_id
from rpt_client_orderline_type rcot
join tick_client tcl on tcl.id = rcot.client_id
where tcl.id = 'CLIENT_TEST'
union
select olt.id
from tick_orderline_type olt
join rpt_client_case rcc on rcc.case_id=olt.case_id
join tick_client cl on cl.id=rcc.client_id
where cl.id = 'CLIENT_TEST'
) olt2 on olt2.id=ol.orderline_type_id
join tick_orderline_type olt on olt.id=ol.orderline_type_id
join tick_case ca on ca.id=olt.case_id
join tick_client cl on cl.id=ca.client_id
join tick_user_case uc on uc.case_id=ca.id
join tick_user u on u.id=uc.user_id
left join tick_promotion_code pc on pc.id=o.promotion_code_id
left join tick_promotion p on p.id=pc.promotion_id
where o.latest_payment_status_change>=dateadd(day,#DayCounter,current_timestamp)
and ((o.latest_payment_status_code = 'ORDER_PAYMENT_OK')
or (o.latest_payment_status_change > dateadd(minute,30,current_timestamp)
and o.latest_payment_status_code = 'ORDER_PAYMENT_WAITING' ))
group by
coalesce(p.name, case when len(ol.action)>1 then substring(ol.action,1,40)+'<br />'+substring(ol.action,41,80) else ca.code end)
, convert(varchar,DateAdd(minute,
15 * ((60 * Datepart(hour, latest_payment_status_change) +
Datepart(Minute, latest_payment_status_change)+
Case When DatePart(second, latest_payment_status_change) < 30
Then 7 Else 8 End) / 15),
DateAdd(day, DateDiff(day, 0, latest_payment_status_change), 0)),126)
order by 1,2
set #DayCounter = #DayCounter - 1;
if ##rowcount <> 0
begin
set #rows = ##rowcount;
print #DayCounter;
end;
end;
The data retrieved is used for a diagram that shows sales per sale-type from the past two days. What I'm trying to achieve now is: When no sales have been made in the past two days (##rowcount = 0), check back a day further each time until data has been found.
The query as it stands now returns something like this (I tried getting the image working, but I somehow am unable to; have a link instead):
https://www.dropbox.com/s/0hculuegrc88c69/SQL_Result.png?dl=0
And it doesn't stop, because for some reason the #rows variable stays 0, despite the query clearly returning rows. Even when using print ##rowcount it returns rows.
SO how do I fix this? Should I use a completely different method?
-Zubaja
It would seem I did not quite understood what my employer meant. He didn't want the error-handling in the SQL, but rather on the website: When no data is found for the past two days, simply show an empty diagram.

SQL - Filtering the Duplicate

I have a sql Query working fine but not able to generate accurate result
My Query Details as follows :
declare #test varchar(500)
SELECT #test=coalesce(#test+',','') + cast(RoleName as varchar) FROM
( select roles.RoleName from LU_BCOMS_usersroles usrroles
inner join LU_BCOMS_roles roles
on roles.roleid = usrroles.Roles_roleid
where Users_Userid='MV10310'
) as Tbl
select repfamily.ProductName as Category,repfamily.Family as SeqChange,repfamily.RepFamily as DescOfChange, req.*,
TaskCompVer =
CASE WHEN req.UpdateByASPM is not null THEN 'Provide PLQM Wish List'
WHEN req.UpdateByASPM is null THEN 'Provide ASPM Wish List'
WHEN req.CreatedBy is not null THEN 'Provide ASPM Wish List'
END
from performa.TX_BCOMS_Request as req
inner join TX_BCOMS_Requestrepfamily family on
family.request_requestid=req.requestid
inner join LU_BCOMS_RepFamily as repfamily on
family.RepFamily_repFamilyid=repfamily.repfamilyid
where req.UpdatedByPLQM is null and (
((CHARINDEX('ASPM',#test)> 0 and CHARINDEX('PLQM',#test)> 0) and req.UpdatedByPLQM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM',#test)> 0 ) and req.UpdateByASPM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM' ,#test)< 0 and CHARINDEX('PLQM',#test) < 0) and req.CreatedBy IS null)
)
Output :
Caterogy SeqCategory DescofChange RequestId TaskCompVer
BIGBEAR BIGBEAR BIGBEAR B14020002 Provide ASPM Wish List
ARCUS3PL KOJN-RE ARCUS3PL B14020002 Provide ASPM Wish List
AURORA Aurora Aurora B14020003 Provide ASPM Wish List
When requestId and TaskCompVer are same there is no need to show 2 records, have to filter something like below..
I need output like below :
Output :
Caterogy SeqCategory DescofChange RequestId TaskCompVer
BIGBEAR,ARCUS3PL BIGBEAR,KOJN-RE BIGBEAR,ARCUS3PL B14020002 Provide ASPM Wish List
AURORA Aurora Aurora B14020003 Provide ASPM Wish List
I need to display the actual as above I tried using STUFF function cannot able to generate the actual output...
May it helpful for you.
CREATE TABLE tempTable(name VARCHAR(50),subjects VARCHAR(50),phone VARCHAR(50))
INSERT INTO tempTable VALUES
('siddique','CRM','123456'),('siddique','Asp.net','9874563'),
('siddique','sql server','44451685'),('Danish','MVC','123456'),
('Danish','sql server','9874563'),('Danish','WCF','44451685'),
('shah g','Account','123456'),('shah g','MBA','9874563'),
('shah g','Math','44451685')
Your simple query select all data
SELECT * FROM tempTable
name subjects phone
siddique CRM 123456
siddique Asp.net 9874563
siddique sql server 44451685
Danish MVC 123456
Danish sql server 9874563
Danish WCF 44451685
shah g Account 123456
shah g MBA 9874563
shah g Math 44451685
Using STUFF to comma seperate your values agaist each name (GROUP BY name)
SELECT
name
,STUFF((SELECT ', ' + subjects
FROM tempTable temp2 WHERE temp2.name=temp1.name
FOR XML PATH('')), 1, 1, '') AS subjects
,STUFF((SELECT '; ' + phone
FROM tempTable temp2 WHERE temp2.name=temp1.name
FOR XML PATH('')), 1, 1, '') AS phones
FROM tempTable temp1
GROUP BY name
DROP TABLE tempTable
Output:
name subjects phones
Danish MVC, sql server, WCF 123456; 9874563; 44451685
shah g Account, MBA, Math 123456; 9874563; 44451685
siddique CRM, Asp.net, sql server 123456; 9874563; 44451685
I needed a similar Query where i needed it the same way... Here is My Query:
SELECT
'All Users' as QuestionOption,
Stuff( (SELECT N'; ' + email FROM users where email>=' ' FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') as QuestionOptionValue
UNION
SELECT 'All Volunteers' as QuestionOption, Stuff( (SELECT N'; ' + U.email FROM
dbo.Users AS U LEFT OUTER JOIN (SELECT up.UserID, MAX(CASE WHEN ppd.PropertyName = \
'Volunteer' THEN up.PropertyValue ELSE '' END) AS Volunteer
FROM
dbo.UserProfile AS up
INNER JOIN dbo.ProfilePropertyDefinition AS ppd ON
up.PropertyDefinitionID = ppd.PropertyDefinitionID and ppd.PortalID = 0 Group By
up.UserID) as upd on U.UserID = upd.UserID Where upd.Volunteer='True' FOR XML
PATH(''),TYPE) .value('text()[1]','nvarchar(max)'),1,2,N'') as QuestionOptionValue
UNION
SELECT 'All Committees' as QuestionOption, Stuff( (SELECT N'; ' + U.email FROM
dbo.USERS AS U LEFT OUTER JOIN (SELECT up.UserID, MAX(CASE WHEN ppd.PropertyName =
'Committee' THEN up.PropertyValue ELSE '' END) AS Committee FROM dbo.UserProfile AS
up INNER JOIN dbo.ProfilePropertyDefinition AS ppd ON up.PropertyDefinitionID =
ppd.PropertyDefinitionID and ppd.PortalID = 0 Group By up.UserID) as upd on U.UserID
= upd.UserID Where upd.Committee >' ' FOR XML PATH(''),TYPE) .value('text()
[1]','nvarchar(max)'),1,2,N'') as QuestionOptionValue
Im not the best at writing them, so you could use mine as an example. my output is:
QuestionOption QuestionOptionValue
All Committees Email#email.com; email#email.com
All Users Email#email.com; email#email.com
All Volunteers Email#email.com; email#email.com
I hope this helps you!
try this,,,,
declare #test varchar(500)
SELECT #test=coalesce(#test+',','') + cast(RoleName as varchar) FROM
( select roles.RoleName from LU_BCOMS_usersroles usrroles
inner join LU_BCOMS_roles roles
on roles.roleid = usrroles.Roles_roleid
where Users_Userid='MV10310'
) as Tbl
select
req.*,
TaskCompVer =
CASE WHEN req.UpdateByASPM is not null THEN 'Provide PLQM Wish List'
WHEN req.UpdateByASPM is null THEN 'Provide ASPM Wish List'
WHEN req.CreatedBy is not null THEN 'Provide ASPM Wish List'
END,
STUFF(
(
select ','+repfamily.ProductName
from TX_BCOMS_Requestrepfamily family
inner join LU_BCOMS_RepFamily as repfamily on family.RepFamily_repFamilyid=repfamily.repfamilyid
where family.request_requestid=req.requestid
FOR XML PATH('') ), 1, 1, '' ) as 'Category',
STUFF(
(
select ','+repfamily.Family
from TX_BCOMS_Requestrepfamily family
inner join LU_BCOMS_RepFamily as repfamily on family.RepFamily_repFamilyid=repfamily.repfamilyid
where family.request_requestid=req.requestid
FOR XML PATH('') ), 1, 1, '' ) as 'SeqChange',
STUFF(
(
select ','+repfamily.RepFamily
from TX_BCOMS_Requestrepfamily family
inner join LU_BCOMS_RepFamily as repfamily on family.RepFamily_repFamilyid=repfamily.repfamilyid
where family.request_requestid=req.requestid
FOR XML PATH('') ), 1, 1, '' ) as 'DescOfChange' ,
repfamily.ProductName as Category,repfamily.Family as SeqChange,repfamily.RepFamily as DescOfChange,
from performa.TX_BCOMS_Request as req
where req.UpdatedByPLQM is null and (
((CHARINDEX('ASPM',#test)> 0 and CHARINDEX('PLQM',#test)> 0) and req.UpdatedByPLQM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM',#test)> 0 ) and req.UpdateByASPM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM' ,#test)< 0 and CHARINDEX('PLQM',#test) < 0) and req.CreatedBy IS null)
)

how to calculate from each row value in sql

I have a table named general_ledger from which I need to show dr_amount, cr_amount and the balance between them as running_balance. That's why I have written a query that is given below. But I am getting the result of each query like the balance only of current row. But I need to produce the result with the remaining balance. Suppose First row dr_balance is 20000 and cr_balance is 5000 and remaining balance is 15000. In second row only cr_balance is 5000. Now the result should be 10000 with the deduction but my result is -5000. I have no idea how to fix this. Can anyone please help me on this? I need your help very much. Here is my query given below :
SELECT '' AS cost_center_id
, '' AS cost_center_name
, '' AS office_code
, CONVERT('2013-02-01',DATETIME) AS transaction_date
, '' AS accounts_head_id
, '' AS account_name
, '' AS opposite_accounts_head_id
, '' AS opposite_account_name
, 'Opening Balance' AS particulars
, tempOpeningBalance.dr_amount
, tempOpeningBalance.cr_amount
, '' AS voucher_no
, '' AS vin
FROM (SELECT IFNULL(mcoa.account_code,'1101010101100321') AS account_code
, IFNULL(mcoa.account_name,'Cash') AS account_name
, IFNULL(mcoa.account_type,'ASSET') AS accountType
, CAST(IFNULL(SUM(IFNULL(maingl.dr_balance,0)),0) AS DECIMAL(27,5)) AS dr_amount
, CAST(IFNULL(SUM(IFNULL(maingl.cr_balance,0)),0) AS DECIMAL(27,5)) AS cr_amount
FROM master_chart_of_accounts AS mcoa
INNER JOIN chart_of_accounts AS coa ON (mcoa.id = coa.master_chart_of_accounts_id AND mcoa.id = 80)
LEFT JOIN general_ledger AS maingl ON (coa.id = maingl.accounts_head_id AND coa.account_code='1101010101100321')
INNER JOIN
( SELECT gl.accounts_head_id, MAX(gl.gl_id) AS max_gl_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
FROM general_ledger AS gl
-- INNER JOIN voucher_info AS vi ON (gl.voucher_info_id = vi.id)
-- WHERE vi.posting_date < '2013-02-01' AND
WHERE gl.transaction_date < '2013-02-01' AND
gl.cost_center_id IN ('BI0000000000000000000001') AND
gl.country_id IN (1) AND
gl.office_code IN ('UG500013') AND
1=1
GROUP BY gl.accounts_head_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
ORDER BY gl.accounts_head_id
) AS tmpgl
ON ( maingl.office_code = tmpgl.office_code
AND maingl.office_type = tmpgl.office_type
AND maingl.accounts_head_id = tmpgl.accounts_head_id
AND maingl.country_id = tmpgl.country_id
AND maingl.cost_center_id = tmpgl.cost_center_id
AND maingl.gl_id = tmpgl.max_gl_id
)
WHERE mcoa.account_status_id = 1 AND
coa.account_status_id = 1
) AS tempOpeningBalance
UNION
SELECT vi.cost_center_id
, cc.center_name AS cost_center_name
, gl.office_code
, vi.posting_date AS transaction_date
, vd.accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.accounts_head_id) AS account_name
, vd.opposite_accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.opposite_accounts_head_id) AS opposite_account_name
, vd.particulars
, gl.dr_amount AS dr_amount -- here to check
, gl.cr_amount AS cr_amount
, vi.voucher_no
, vi.vin
FROM general_ledger AS gl
INNER JOIN voucher_info AS vi
ON (gl.voucher_info_id = vi.id)
INNER JOIN cost_center AS cc
ON (vi.cost_center_id = cc.id)
INNER JOIN voucher_details AS vd
ON (vi.id = vd.voucher_info_id)
INNER JOIN chart_of_accounts AS coa
ON (vd.accounts_head_id = coa.id)
WHERE vi.posting_date BETWEEN '2013-02-01' AND'2013-02-28'
AND vi.voucher_status_id = 3
AND vd.status_id = 1
AND vi.office_code = 'UG500063'
AND coa.account_code='1101010101100321'
AND coa.cost_center_id = 'BI0000000000000000000001'
ORDER BY cost_center_name
, office_code
, transaction_date;
Use a variable like this
SET #running_balance=0;
SELECT dr_amount AS dr_amount
, cr_amount AS cr_amount
, #running_balance := (#running_balance + dr_amount - cr_amount)
FROM general_ledger