ssrs tips&tricks

of 55/55

Post on 10-Apr-2016




3 download

Embed Size (px)


SQL Server Reporting Services


SQL Server Reporting Services


Introduction to ssrs

SSRS or SQL server Reporting Services which is also called Microsoft SQL reporting, is a component of the Microsoft BI stack.

The Microsoft Business Intelligence Stack mainly consists of SQL Database Engine, SSRS, SSAS, SSIS and other tools

SSRS is a set of readymade tools, which help you to create, deploy and manage reports.

You can extend reporting functionality using C# and VB as programming languages.

Microsoft SSRS or Business Intelligence SSRS, lets you create very rich reports (Tabular/Graphical/Interactive/free-form) from various data sources with rich data visualization (Charts, Maps, sparklines).

All these reports can be viewed via a web browsers.

SSRS allows are reports to be exported in various formats (Excel, PDF, word etc.)

SSRS allows reports to be delivered via emails or dropped to a share location in an automated fashion.

SSRS provides a host of security features, in order to control, who sees which reports etc.

Section A

How to install ssrsDouble-click the SQL Server2012 installationmedia. Click the Installationlink on the left to view the Installationoptions. Click the top linkNew SQL Serverstand-alone installationor add features to an existinginstallation.

Follow the SQL ServerSetup wizard until you get to the InstallationType screen. At that screen, selectAdd features to an existinginstance of SQL Server2012. ClickNextto move to the Feature Selectionpage. SelectReporting Services NativeandSQL ServerData Tools. If theManagement Toolshave not been installed, go ahead and choose them as well.

Continue through the wizard and reboot the computer at the end of the installationif instructed to do so.Configure Reporting ServicesIf you installed Reporting Services during the installationof the SQL Serverinstance, SSRSwill be configured automatically for you. If you install SSRS later, then you will have to go back and configure it as a subsequent step.ClickStart>All Programs>Microsoft SQL Server2012>Configuration Tools>Reporting Services Configuration Manager>Connecton the Reporting Services Configuration Connection dialog box.

On the left-hand side of the Reporting Services Configuration Manager, clickDatabase. Click theChange Databasebutton on the right side of the screen.

SelectCreate a new report server databaseand clickNext.

Click through the rest of the wizard accepting the defaults. This wizard creates two databases: ReportServer, used to store report definitions and security, and ReportServerTempDB which is used as scratch space when preparing reports for user requests.Now clickWeb ServiceURLon the left-hand side of the Reporting Services Configuration Manager. Click theApplybutton to accept the defaults. If theApplybutton has been grayed out, move on to the next step. This step sets up the SSRSweb service. The web service is the program that runs in the background that communicates between the web page, which you will set up next, and the databases.

The final configuration step is to select theReport ManagerURLlink on the left. Accept the default settings and clickApply. If theApplybutton was already grayed out, this means the SSRSwas already configured. This step sets up the Report Managerweb site where you will publish reports. You may be wondering if you also must install a web server on your computer. SQL Serverdoes not require that the Internet Information Server(IIS), the Microsoft web server, be installed to run Report Manager.

ClickExitto dismiss the Reporting Services Configuration Managerdialog box.

Built in Expressions or functions used in ssrsTypes of Expressions


Operators - Arithmetic, Comparison, Logical

Common Functions - Text, Date & Time, Math, Inspection, Program Flow, Aggregate, Financial, Conversion, Miscellaneous


Global expressions executes/works in Page Header and Footer parts only.ExecutionTimeshows date and time at when report executes

PageNumbershows page number of each and every page but allowed only in page header and footer

ReportNamedisplays name of the active report what name we have assigned to the active report

UserIdshows current user name like saxony/Prashant.RaiLanguagedisplays language like US-English



^power of*multiplication/divides two numbers and returns a floating point result\divides two numbers and returns a integer resultModdivides two numbers and returns remainder only+adds two numbers and concatenation for two strings-subtraction and indicates negative value for numeric values


Known operators :< >=

Likecompares two strings and return true if matched or else returns False. Ex: =Fields!Title.Value Like Fields!LoginID.Value

Iscompare two object reference variables Ex: = Fields!Title.Value Is Null


+ and &symbols uses for concatenation


Known:And, Not, Or

XorSELECT * FROM users where firstname = 'Prashant' XOR lastname = 'Rai'

AndAlsoFirst condition will check first and if it is true only, goes to next or else it won't need to check. Because our execution time is saving in a logical operation in which more conditions is combined using AndAlso function.

OrElsesame like above


The rest of the functions can be accessed by clicking on Expression on any report item, which looks like following:


The following section (pg.16-pg.46) will introduce you to some tips and tricks which are based upon, basic/inbuilt functions and expressions that we have in SSRS and which I have garnered over a period of time. This section is recommended for anyone who wants more out of standard SSRS expressions.

EMBEDDED CODE FOR CELL COLORING (CONDITIONAL FORMATTING)Bring up the Report Properties (by right clicking outside the report in Layout view)

Now go to the Code tab and write in this code:Function GetColour(ByVal Amount As Double) As StringIf Amount < 5000000 Then GetColour = "Red"ElseIf Amount >= 5000000 And Amount < 7500000 Then GetColour = "Orange"Else GetColour = "Green"End IfReturn GetColourEnd Function

Now Insert either of these formula into the Cells Colour Format=Code.GetColour(Fields!TotalDue.Value)=Code.GetColour(Me.Value)

SHOW PERCENTAGES ON PIE CHARTBring up the Chart Properties (Right Click the Chart object and select properties)

Now click theEditbutton for the Values section and go to the Point Labels tab

Uncheck Auto to get percentages on outside (the inside square of 9 put labels in Pie Chart, the other are on the outside) and check theShow point labelsboxNow the formula to enter into theData labeltext box is:=Sum(Value) / Sum(Value, "ChartDataset")In this case the formula is:=Sum(Fields!TotalDue.Value) / Sum(Fields!TotalDue.Value,"pRepSalesOrdersByMonth")And theLabel Stylebutton opens up the label formatting properties

And this is the final product

T-SQL ISNULL FUNCTION EQUIVALENTUsing the VB IIF Function use the following expression=IIF(Field!FieldName.Value Is Nothing, "Value for True", "Value for False")e.g.

SHOW TICK/CROSS BOX INSTEAD OF TRUE/FALSE OR 1/0Convert the Boolean (or 1/0) field to "R" for True / 1 and "Q" for False / 0You can do this either in SQL or using an IIF expressionSQL,CASEWHENBooleanField=1THEN'R'ELSE'Q'ENDASBooleanFieldIIF Expression=IIF(Fields!BooleanField.Value =True,"R","Q")The original field doesn't necessarily have to be Boolean e.g. Does final score pass exam:=IIF(Fields!FinalScore.Value >= 50,"R","Q")Now just format the textbox to Wingdings2

And this is what you get:

LINK POSTCODE OR ADDRESS TO GOOGLE MAPSOpen the textbox properties for the field you want to have the link:

And select theActiontab:

Open theGo to URLexpression builder and insert the following expression:="javascript:void('"& Fields!PostalCode.Value &"','_blank','scrollbars=auto, resizable=yes, status=no'))"This will open google maps in a new IE window using the results of the field as the search criteriaClick here for more info on the javascript open methodOr alternatively you can use the expression without the javascript to open in the current IE=""& Fields!PostalCode.ValueThis is just one application of the Jump to URL functionality, this can be used in many ways, e.g. Linking to customer orsupplier websites (providing you have the website address as a field in reports dataset)

HANDLING DIVIDE BY ZERO ERRORBring up the Report Properties (by right clicking outside the report in Layout view)

Now go to the Code tab and write (or copy and paste) in this code:Function CalculateFraction(ByVal Numerator As Double, ByVal Denominator As Double) As DoubleIf Denominator= 0 Then CalculateFraction = 0Else CalculateFraction = Numerator / DenominatorEnd IfReturn CalculateFractionEnd Function

Now insert the following expression into the desired textbox and format according:=Code.CalculateFraction(Fields!Numerator.Value, Fields!Denominator.Value)You could also use the following IIF expression:=IIF(Fields!Denominator.Value = 0, 0, Fields!Numerator.Value / IIF(Fields!Denominator.value = 0, 1, Fields!Denominator.Value))But the best thing about using the Embedded Code it's easier to use and reusable.

PARAMETER TO CONTROL ROW/COLUMN/TABLE VISIBILITYAdd in a new parameter, all properties are fairly arbitrary as long as the parameter has 2 values, 1 for viewing a particular column or groups of columns

Right click on the column head and select column visibility

Enter the following expression in show or hide based upon expression.=IIF(ParameterForColumnVisibilty = Yes,False,True)Which in the example is:=IIF(Parameters!ViewIssueCell.Value = 1,False,True)

The same can be done to control the visibility for rows and the entire table.

ALTERNATING ROW COLORS IN A TABLEOn the table select the row to bring up the properties

and enter the following expression into theBackgroundColorproperty=IIF(RowNumber(Nothing)Mod2,"LightCyan","White")Or whatever colors you prefer.HAVE TEXT ON MULTIPLE LINES IN A TEXTBOXUse Chr(10) and Chr(13) when you want to start text on the next line,e.g. use the expression:="First line of text" & Chr(13) & Chr(10) & "Second line of text"The problem here is when you export to Excel you get a box for Chr(13)

This is fixed by leaving out the Chr(13)="First line of text" & Chr(10) & "Second line of text"


For instance, you want your data to look like this:RankCaptainLieutenantSergeantCorporalPrivate

To handle this we can embed a non truncating space character by using an ASCII key combination code. To embed this ASCII key code we would hold the ALT key, type 0160 and then let go of the ALT key.So to do this in our report, in the Reporting Services table, right click on the textbox with the problem, select (fx) Expression. Then in the Edit Expression editor use the REPLACE function to embed the non-truncating space with the normal one as follows:=REPLACE(Fields!Rank.Value," "," ") -- (The first value between the double quotes is a space and the second value between the double quotes is the ALT-0160 combination code.)

After we have made this function change and redisplay the report our hierarchy should be displayed properly as needed.

DEFINE A REPORT CONSTANTBring up the Report Properties (by right clicking outside the report in Layout view)

Now go to the Code tab and write in this code:Public Const PI = 3.14Now in any report expression you can use:=Code.PI

DISPLAY A MESSAGE WHEN REPORT RESULT SET IS EMPTYBring up the table propertiesand select the Visibility tab

Set theInitial visibilityto the following expression:=IIF(Count(Fields!AnyFieldintheDataset.Value,"DatasetName") = 0,True,False)Which in the example above would be:=IIF(Count(Fields!CountryRegionCode.Value,"pRepNoRowsReturned") = 0,True,False)Create a textbox and enter the message you want to display when the resultset is empty, now the the visibility of the text box to the same as the table BUT with the True and False switched around, so in the example above:=IIF(Count(Fields!CountryRegionCode.Value,"pRepNoRowsReturned") = 0,False,True)This will also work with other objects e.g. Matrix, Chart, List, and RectangleAnother way of doing it is selecting the tablix/matrix properties and setting a message as shown below:

SETTING PARAMETERS DEFAULT VALUE ISSUEWhen setting the parameter default value you can simply add a value into the Default Values - Non-queried expression box like this:

Now when you preview the report in the design environment this parameter will default to 1 and if you deploy this report to Report Manager and view it from there it will also default to 1.The problem arises when you want to change it, if in the example you wanted to change the default value to 0 and you just replaced the 1 with a 0 then when you preview in the design environment the report will recognise this change and default to 0 but when you deploy the report it will still default to 1 (the value it was set to when it was first deployed)This is easily fixed you just need to include and equals sign first.

Now when you re-deploy the report it will update the RDL on the Report Server.For text (and dates, although using expression it better for dates) you just need to use marks e.g.="Yes"

CREATE A DRILL DOWN TABLEDragthe table object on to the report detail area and put the field you want to be at the bottom of the drill down into the first textbox (In this example the table will drill-down from Continent - (Country/Area) - Year - Date) and then right-click on the detail row selector and select add group:

Select Fields!Continent.Value as the expression to group on

Now bring up the textbox properties for the far left textbox in the newly created Continent group and set the Value to Fields!Continent.Value and the Name to Continent

Now repeat this process for the next group Fields!Name.ValueIf you have values you wish toTotal for each group add them in on the same line as the relevant group using the Sum() function on all but the detail line

If (for example) your dataset when down to individual Invoice level you could add more columns to the right and then put the Invoice details (Date, Reference Number, Customer etc) on the detail lineNote: You can only use Aggregate functions on the Groupings lines (other than the Field its been grouped on)Now to give the table the drill-down effect you need to set each rows visibility to Hidden and the Toggle Item to the textbox above, so for the detail row we set the Toggle Item to the OrderYear textbox (OrderYear row to Name, Name row to Continent) click on the Detail row to get the properties

If you want to have totals (at the bottom) for each grouping these would go in the groups below the detail line and these would also need to have their visibilities set, I usual just delete them.One effect I like the look of is to indent each group (more than the other) by change the textbox Left property on the Format tab:

Once these have all been set you ready to deploy and it should look something like:

And something like this from Report Manager

DISPLAY ALL RECORDS ON ONE PAGEThe default Interactive size is set to 11 inches and whatever records can fit into it that is what SSRS display to us.

Let's change the Height to 0 Under InteractiveSize Property under Report properties and deploy our report and see if it is showing all records on one page.

Report display

As we can see that the next page button is not available as all the records are shown on one page.

Note:Displaying all the records on one page can take long time to display. You want to make sure you do not have millions of records to shown on a page. In those cases the explorer can crash or can take forever to display. Instead of displaying all the records on one page you might want to increase Height from 11 inches to another number to display more records on each page.


1. PagingWhen creating a report with sub reports paging should be added to the top level report. The paging inside the sub report looks fine on screen but is ignored when exporting to PDF.2. No DataWhen there is no data in a sub report the report will not show. If you have a report where you have paging between sub-reports you will end up with a page break, but then no report, which means you get an empty page in your report. The way to force you report to render is to create an empty dataset, with1select 1

as the SQL. This will always execute and force the sub-report to always render

DISPLAYING DATA IN SSRS TOOLTIPSTooltips are often used to help the viewer gain a better understanding of what's displayed. This entry discusses the use of datawithin tooltips.At a glance, the viewer sees the approximate percentage for each school based on the X axis:In addition to the overall comparison of totals between schools, the exact percentage for each school is also useful information. To keep this chart uncluttered, let's choose to provide the exact percentage usinga tooltip.Right-click the chart,select Series Properties, and open thetooltip expression (fx) window. This expression uses theFields Collection (i.e., thedata) as well as text:

The above expression results in the viewer seeing the following:

Regarding the FormatNumber function:source datais stored as decimal(10,2)which translates perfectly for display on the X axis when the axis is formatted as a percentage. However, that data type doesn't look very nice in a label. To handle this, firstmultiply it by 100 (which took .81 to 81.00), then used the FormatNumber function with 0 decimal places (which took my 81.00 to 81), and finally concatenatedthe % symbol along with some descriptive text.

HOW TO ADD AN ELSE TO SWITCH STATEMENTTwo commonly-used functions in Reporting Services are theIIF()and theSwitch(). These are two functions of the Program Flow type, or Decision Functions.TheIIF()works in the following way.If evaluates to true then gets executed, else gets executed.Heres a simple example:=IIf(Fields!YearlyIncome.Value >= 600,"High","Low")Using this expression, the "High" string is returned when the value of the YearlyIncome field is equal to or above 600, while the string "Low" is returned when the value is below 600.Now have a look at the following example. It has been nicely structured with indentation and line breaks to make reading easier.=IIF( Sum(Fields!LineTotal.Value) >= 100, "Violet", IIF() ( Sum(Fields!LineTotal.Value) < 25, "Transparent", "Cornsilk" ))As you see, it shows a nested IIF inside another one. Imagine that there were several more nestings and that line breaks were not used by the coder. Would be a nightmare to read, right?Thats why theSwitch()was invented. The description for the Switch function reads:Evaluates a list of expressions and returns an Object value corresponding to the first expression in the list that is True.Heres a simple example:=Switch( Fields!State.Value = "OR", "Oregon", Fields!State.Value = "WA", "Washington")This expression says that if the value for the State field is "OR" then the Switch function will return "Oregon", and so onNow, to get to the point of this section, the Switch function does not contain an ELSE part like the IIF does.If you read the Switchs description closely, it says that it will returnthe first expression in the list that is true. So each expression is evaluated in the order that they are passed to the function. To get ELSE-like behavior we would need an expression that evaluates to True but only when all other expressions are False. So, why not use True as expression? Its the simplest expression that I can think of and it does the works!Have a look at the following, its a rewrite of the last IIF example mentioned earlier.=Switch( Sum(Fields!LineTotal.Value) >= 100, "Violet", Sum(Fields!LineTotal.Value) < 25, "Transparent", True, "Cornsilk")CALCULATING RUNNING TOTALSThe syntax for RunningValue function goes like this RunningValue(expression, function, scope) expression: The expression on which to perform the aggregation, for example,[Quantity]. function: The name of the aggregate function to apply to the expression, for example-Sum. scope:The name of a dataset, data region, group or Nothing.See the table below and RunningTotal column which is Cumulative SUM of Quantity column.ShipIdOrderIdShipDateQuantityRunningTotal

112009-02-01 12:06:16.8201010

212009-02-02 16:16:16.8201525

322009-02-01 13:26:16.8202045

422009-02-03 17:40:16.8201257

522009-02-04 13:05:16.8201572

632009-02-03 14:25:16.8202597

732009-02-04 15:50:16.82050147

832009-02-05 19:40:16.82030177

942009-02-06 15:30:16.82020197

1042009-02-07 16:20:16.82010207

1152009-02-05 17:05:16.82035242

For achieving that in SSRS, add extra column in your Reports Layout Page and put following expression in it-=RunningValue(Fields!Quantity.Value, Sum, Nothing)

But what about when you want the RunningTotals for group of records? Like for above example you want the Running Totals for each orderId separately. See the table below :ShipIdOrderIdShipDateQuantityRunningTotal

112009-02-01 12:06:16.8201010

212009-02-02 16:16:16.8201525

322009-02-01 13:26:16.8202020

422009-02-03 17:40:16.8201232

522009-02-04 13:05:16.8201547

632009-02-03 14:25:16.8202525

732009-02-04 15:50:16.8205075

832009-02-05 19:40:16.82030105

942009-02-06 15:30:16.8202020

1042009-02-07 16:20:16.8201030

1152009-02-05 17:05:16.8203535

Now for achieving that you need do followings : First go to Report Layout page and add a new Group. Give some name to the group. If you dont gave any name the default name would be something like table1_Group1. Just note that. And add OrderId to Group On expression. Now change the expression at RunningTotal column as=RunningValue(Fields!Quantity.Value,SUM,"table1_Group1") Now if you have noticed I have replaced the scopeNothingto Group name table1_Group1 .Well after adding the extra group in the report you might see blank spaces after every OrderId change. If you dont want those blanks and want continuous report, then go to the property page of the new group added and set Visible to false.REPEAT TABLE HEADER ON EACH PAGE IN SSRSIn this scenario, we have to set the some properties ofstatic memberof the row groups.To see the static members of the row groups of the tablix, select tablix and click on the small drop down arrow on the right side of theRow Groups/Columns Groupsheader. Then selectAdvanced Mode.Please see below screenshot.

Now you can see thestatic membersof row groups. Now select1ststatic member. After selecting 1st member, top left cell of thetablixwill be selected in the report designer.

Now press F4 or manually open property page. In that, set propertyRepeatOnNewPagetoTrue. Also setKeepWithGroupproperty toAfter.

Now run your report. You will see that your table header will repeat on every page of report.If still issue is not solved then setFixedDataproperty toTruein property page of first static member in row group. It will reproduce table header on every page of report.

Sometimes you dont need to set all three properties, but it doesnt do any harm so lets set all three properties.

47 | Page