Showing posts with label SSRS. Show all posts
Showing posts with label SSRS. Show all posts

Friday, 17 April 2020

Exclude Zero from SSRS Expression

Hello Guys,

Please check out below tips for excluding the zero from the SSRS Expression.

=Avg(IIF(Field!FieldName.Value ="0", Nothing,Field!FieldName.Value))

Above expression is also works for the SUM, MIN, MAX and etc..

if you have any query feel free write on the comment.

Wednesday, 11 July 2018

How to get a list of SSRS schedules for subscriptions

Hi Guys,

below script gives you the list of subscription set on each and every report of SSRS.


use ReportServer

select c.Name,
c.Path,
s.StartDate,
s.NextRunTime,
s.LastRunTime,
s.EndDate,
s.RecurrenceType,
s.LastRunStatus,
s.MinutesInterval,
s.DaysInterval,
s.WeeksInterval,
s.DaysOfWeek,
s.DaysOfMonth,
s.[Month],
s.MonthlyWeek
from dbo.catalog c with (nolock)
inner join dbo.ReportSchedule rs
on rs.ReportID = c.ItemID
inner join dbo.Schedule s with (nolock)
on rs.ScheduleID = s.ScheduleID
order by s.LastRunTime desc 

If you find any difficulty then reply on the comment box.
I will revert as soon as possible.

Thanks for the reading.

Saturday, 2 December 2017

SSRS Pass a Report Parameter Within a URL

You can pass report parameters to a report by including them in a report URL. These URL parameters are not prefixed because they are passed directly to the report processing engine.

Reference : 
https://docs.microsoft.com/en-us/sql/reporting-services/pass-a-report-parameter-within-a-url


http://localhost/Reports/Pages/Report.aspx?ItemPath=%2f%5bQuality+Sales+Report%5d%2fCP+Quailty+Sales+Details+Report+Preview&ViewMode=Detail

Above link is your report server link which provide you to make subscription and etc.
Instead of above link try below

Go to http://localhost/Reportserver find your report in above link and pass "&ID=(value) at the end of the url or

http://rpt.Server.local/Reportserver/Pages/Report.aspx?ItemPath=%2f%5bQuality+Sales+Report%5d%2fCP+Quailty+Sales+Details+Report+Preview&ID=(value)

Friday, 10 November 2017

Delete encryption key from report server

If unable to delete encryption key from SQL server reporting service configuration manager, to delete it manually use below stored procedure.

use ReportServer

exec DeleteEncryptedContent


If you find any difficulty, feel free revert.
Above stored procedure is predefined in Report Server.

Monday, 6 July 2015

Print / Export SSRS report in ASP.NET | Print Reportviewer Report using JavaScript / Jquery

Create a report from following post 
http://ssrsmegabits.blogspot.in/2015/06/ssrs-report-in-aspnet-example.html

Now we will update above solution for Print SSRS reports using JavaScript and Export it in PDF Format.

Design:

<div id="result"></div>
    <div id="content">
    <input id="btnPrint" type="button" value="Print Report" onclick="PrintReport();" />
    <asp:Button ID="btnExportPDF" runat="server" Text="PDF"
            onclick="btnExportPDF_Click" />
    <rsweb:ReportViewer  Width="100%" ShowToolBar="false" ID="rptvMyReport" runat="server" AsyncRendering="false">
    </rsweb:ReportViewer>

    </div>

Here we have two div with id 'result' and 'content'.
In result div we will copy the content div in the print format and call print method in javascript.
One button added for export report in PDF Format.

javascript Code:

This code for Print ssrs report.

<script type="text/javascript">   
        function PrintReport() {
            var viewerReference = $find('<%=rptvMyReport.ClientID%>');

            $('#result').empty();
            var stillonLoadState = viewerReference.get_isLoading();

            if (!stillonLoadState) {
               
                var reportArea = viewerReference.get_reportAreaContentType();
                if (reportArea == Microsoft.Reporting.WebFormsClient.ReportAreaContent.ReportPage) {
                    $('#rptvMyReport').clone().prependTo("#result");
                    //copy reportviewer report in div
                    $('#content').hide();
                    $('#result').show();
                    //hide reportviewer containing div and show copied div  
                    window.print();
                     //Open Print dialog
                    $('#content').show();
                    $('#result').hide();
                    //Reset 
                }
            }   
        }
     </script>

Now we will added this code in code behind to get SSRS report in PDF Format.

protected void btnExportPDF_Click(object sender, EventArgs e)
        {
            Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;
            string Title = "UserList " + Convert.ToString(DateTime.Now);
            byte[] bytes = rptvMyReport.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + Title + "." + extension);
            Response.BinaryWrite(bytes); // create the file
            Response.Flush();
        }

Note : If you want to get report in  WORD and EXCEL format then update it as following.

For Excel:
byte[] bytes = rptvMyReport.LocalReport.Render("EXCEL", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

For Word:
byte[] bytes = rptvMyReport.LocalReport.Render("WORD", null, out mimeType, out encoding, out extension, out streamIds, out warnings);


Now check the output, you will get the print and export working in ASP.NET.

Friday, 26 June 2015

SSRS Report in ASP.NET Example

Following steps are given to create a SSRS(RDLC) Report in ASP.NET



1)      Create table "UserList" in Database

2)      Create Connection String in Web.Config
<connectionStrings>
    <add name="constr" connectionString="<Databaseconnection>" ProviderName="System.Data.SqlClient"/>
</connectionStrings>

3)      Add httphandler to web.config.
<system.web>
    <httpHandlers>
      <add path="Reserved.ReportViewerWebControl.axd" verb="*"
      type="Microsoft.Reporting.WebForms.HttpHandler,
      Microsoft.ReportViewer.WebForms, Version=10.0.0.0,
      Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"
      />
    </httpHandlers>
</system.web>
<system.webServer>
    <handlers>
      <add name="ReportViewerWebControlHandler"
      preCondition="integratedMode"
      verb="*" path="Reserved.ReportViewerWebControl.axd"
      type="Microsoft.Reporting.WebForms.HttpHandler,
      Microsoft.ReportViewer.WebForms, Version=10.0.0.0,
      Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
      />
    </handlers>
  </system.webServer>

4)      Create empty ASP.NET Application.
5)      Crate Report Folder, Named it “Reports”
6)      Add SSRS Report(.rdlc) in report folder, Named it “MyReport”.
7)      Add Dataset (.xsd) in report folder, Named it “MyReportUser”.
8)      Design Dataset (add Datatable and add column in datatable as same in SQL Table.

9)      Open Myreport.rdlc file and add DataSet “MyReportUser” in Report Data Section.

10)   Design report as per your requirement.

11)   Add script manager and report viewer to aspx page as shown below:
<form id="form1" runat="server">
    <asp:ScriptManager runat="server">
    </asp:ScriptManager>
    <div>
    <rsweb:ReportViewer Width="100%" ShowToolBar="false" ID="rptvMyReport" runat="server">
    </rsweb:ReportViewer>
    </div>
    </form>
12) Add following namespaces

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Reporting.WebForms;
using SSRSReportExample.Reports; //To Access Reports folder Dataset

13) Add to Code Behind

string str = ConfigurationManager.ConnectionStrings["constr"].ToString();
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                getUserList();//Call report at page load
            }
        }

        private void getUserList()
        {
            SqlConnection con = new SqlConnection();//Create SQL Connection Object
            MyReportUser dsUserList = new MyReportUser();//Create DataSet Object
            try
            {
                con.ConnectionString = str;
                SqlDataAdapter sda = new SqlDataAdapter("select * from UserList", con);
                con.Open();
               
                sda.Fill(dsUserList, "UserList");//bind data to DataSet
                if (dsUserList.Tables[0].Rows.Count > 0)//if bind is successfull then execute
                {
                    rptvMyReport.ProcessingMode = ProcessingMode.Local;
                    rptvMyReport.LocalReport.ReportPath = Server.MapPath("~/Reports/MyReport.rdlc");
                    rptvMyReport.LocalReport.DataSources.Clear();//Clear previous applied Datasource
                    ReportDataSource rptDataSource = new ReportDataSource("UserList", dsUserList.Tables[0]);//Create Report Datasource and add Dataset in it.
                    rptvMyReport.LocalReport.DataSources.Add(rptDataSource);
                }
            }
            catch { }
            finally { con.Close(); }
        }
14) Build your application and check the result.


Monday, 30 March 2015

SSRS - Check Report Rendering Time

Here SQL Reporting Server have log our reports processing time in table and We have a View "ExecutionLog3" in SQL Server.

Following Query will gives us the total time (Minutes) taken by the SSRS report to generation.

This Query help us to find out the exact time of every stage.

  1. TimeDataRetrieval : Give us time to data retrieval by SQL Server
  2. TimeProcessing : Give us time processed to bind with the DataSet.
  3. TimeRendering : Give us time to rendering(Formatting) the SSRS report.


use ReportServer

select top 10 
  InstanceName,
  ItemPath,
  UserName,
  CAST((TimeDataRetrieval)as numeric(18,2))/60000 TimeDataRetrieval,
  CAST((TimeProcessing)as numeric(18,2))/60000 TimeProcessing,
  CAST((TimeRendering)as numeric(18,2))/60000 TimeRendering,
  CAST((TimeDataRetrieval+TimeProcessing+TimeRendering)as numeric(18,2))/ 60000 [Total_Time(Minutes)]
 from ExecutionLog3




Tuesday, 17 March 2015

SSRS - Temporary Disable All Subscriptions

Temporary Disable Subscriptions


The InActiveFlags field in dbo.Subscriptions can be 1 or 0 (true or false).


--Code Snippet
--To Check Subscription Status.
USE ReportServer
SELECT dbo.Subscriptions.Description,
       dbo.[Catalog].Name,
       dbo.Users.UserName,
       InactiveFlags
FROM dbo.Subscriptions 
     INNER JOIN dbo.[Catalog] 
     ON dbo.Subscriptions.Report_OID = dbo.[Catalog].ItemID 
     INNER JOIN dbo.Users 
     ON dbo.Subscriptions.OwnerID = dbo.Users.UserID

------------------------------------------------------------------------------------------

--Temporary disables subscriptions while data warehouse is unavailable

UPDATE dbo.Subscriptions
SET InactiveFlags = 1
GO
--After this you can find, all the subscription where disabled until you again enable it.

Again enable subscriptions.

UPDATE dbo.Subscriptions
SET InactiveFlags = 0

Thursday, 26 February 2015

SSRS wrap/line break row and column within group

This SSRS solution is for making row/column break in grouping.

For the result we will consider following queary as an Example:

SQL Query :-

select '1' [Rank],'Product1' Product
union all
select '2','Product2'
union all
select '3','Product3'
union all
select '4','Product4'
union all
select '5','Product5'
union all
select '6','Product6'

and using above we get the result as shown below
Result :-
Rank       Products
1          Product1
2          Product2
3          Product3
4          Product4
5          Product5
6          Product6

Now in SSRS we need to show the result as shown below and for that we will use report Builder and creating new report.
So we have to create a dataset using above query and create one table as shown below:

Now add Row Group and Column Group as shown

In Row Group
1.  Go to the properties and add group expressions
2.  Add this =(Fields!Rank.Value- 1) Mod 3
In Column Group
1.  Go to properties of Column Group
2.  Add this to expression =Floor((Fields!Rank.Value - 1) / 3)

See the result as shown Below:

Wednesday, 11 February 2015

SSRS Download all reports from report server using SQL

Before download of report you have to make some config changes given below

-- Allow advanced options to be changed.

EXEC sp_configure 'show advanced options', 1
GO

-- Update the currently configured value for advanced options.
RECONFIGURE
GO

-- Enable xp_cmdshell

EXEC sp_configure 'xp_cmdshell', 1
GO

-- Update the currently configured value for xp_cmdshell
RECONFIGURE
GO

-- Disallow further advanced options to be changed.

EXEC sp_configure 'show advanced options', 0
GO
-- Update the currently configured value for advanced options.

RECONFIGURE

GO

The following code is for download the reports from report server


DECLARE @FilterReportPath AS VARCHAR(500) = NULL 

DECLARE @FilterReportName AS VARCHAR(500) = NULL

--reports to be downloaded..
DECLARE @OutPath AS VARCHAR(500) = 'C:\\Reports\\Download\'
--Make sure this folder exist in drive
--Used to prepare the dynamic query

DECLARE @TSQL AS NVARCHAR(MAX)

--Simple validation of OutputPath; this can be changed as per ones need.


IF LTRIM(RTRIM(ISNULL(@OutPath,''))) = ''

BEGIN

  SELECT 'Invalid Output Path'

END

ELSE
print @OutPath

BEGIN

   --select * from Catalog
   SET @TSQL = STUFF((SELECT

                      ';EXEC master..xp_cmdshell ''bcp " ' +
                      ' SELECT ' +
                      ' CONVERT(VARCHAR(MAX), ' +
                      '       CASE ' +
                      '         WHEN LEFT(C.Content,3) = 0xEFBBBF THEN STUFF(C.Content,1,3,'''''''') '+
                      '         ELSE C.Content '+
                      '       END) ' +
                      ' FROM ' +
                      ' [ReportServer].[dbo].[Catalog] CL ' +
                      ' CROSS APPLY (SELECT CONVERT(VARBINARY(MAX),CL.Content) Content) C ' +
                      ' WHERE ' +
                      ' CL.ItemID = ''''' + CONVERT(VARCHAR(MAX), CL.ItemID) + ''''' " queryout "' + @OutPath + '' + CL.Name + '.rdl" ' + '-T -c -x'''
                    FROM
                      [ReportServer].[dbo].[Catalog] CL
                    WHERE
                      CL.[Type] = 2 --Report
                      AND '/' + CL.[Path] + '/' LIKE COALESCE('%/%' + @FilterReportPath + '%/%', '/' + CL.[Path] + '/')
                      AND CL.Name LIKE COALESCE('%' + @FilterReportName + '%', CL.Name)
                    FOR XML PATH('')), 1,1,'')

  --Execute the Dynamic Query
  print @TSQL

  EXEC SP_EXECUTESQL @TSQL

END