Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a...

89
Groups in SSRS 2008 In Report Designer, Groups are created to organize data on the report or to calculate aggregate summaries. An understanding how to define groups and use group features helps you design reports that are more concise and communicate summarized data in a more compact format. We also use Groups in SSRS reports to provide Drill-down features. In this article, I'll walk you through SSRS Groups to create a report shown in below image: STEP1: Add new report in Report Server project and rename it to GroupsInSSRS.rdl. Create new Shared DataSource for database AdventureWorksDW2008R2. Click here to download AdventureWorksDW2008R2 database. STEP2: Create a new dataset dsMain with Shared Data Source. Use below query for this dataset:

Transcript of Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a...

Page 1: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Groups in SSRS 2008 In Report Designer, Groups are created to organize data on the report or to calculate aggregate summaries. An understanding how to define groups and use group features helps you design reports that are more concise and communicate summarized data in a more compact format.

We also use Groups in SSRS reports to provide Drill-down features. In this article, I'll walk you through SSRS Groups to create a report shown in below image:

STEP1: Add new report in Report Server project and rename it to GroupsInSSRS.rdl. Create new Shared DataSource for database AdventureWorksDW2008R2. Click here to download AdventureWorksDW2008R2 database.

STEP2: Create a new dataset dsMain with Shared Data Source. Use below query for this dataset:SELECTD.CalendarYear AS [Year],D.CalendarQuarter AS [Quarter] ,D.EnglishMonthName AS [Month],D.FullDateAlternateKey AS [Date],P.EnglishProductName AS [ProductName],C.FirstName + LastName AS [CustomerName]

Page 2: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

,ST.SalesTerritoryRegion AS [SalesRegion],ST.SalesTerritoryCountry AS [SalesCountry],F.SalesOrderNumber AS [OrderNumber],F.SalesAmount FROM FactInternetSales FJOIN DimProduct P   ON P.ProductKey = F.ProductKey JOIN DimCustomer C   ON C.CustomerKey = F.CustomerKey JOIN DimDate D   ON D.DateKey = F.OrderDateKey JOIN DimSalesTerritory ST   ON ST.SalesTerritoryKey = F.SalesTerritoryKey 

STEP3: Drag and drop a table control and select CustomerName, OrderNumber, and SalesAmount fields in the table. 

STEP4: Select table detail row --> Right click --> select Add Group --> Row Group --> Parent Group

STEP5: Select ProductName in Tablix group window and check add group header check box. Click OK and sace changes.

Page 3: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Now you can see Product Group in the table as shown below:

Delete Group1 Column and rename Customer Name as Particulars. Select ProductName in Product Group as shown below:

STEP6: Select ProductName group and add one more group for SalesCountry in similar way mentioned atstep5. Delete the group column and select SalesCountry in CountryGroup as shown below:

STEP7: In the same way add Groups for the following Fields:

SalesRegion Date Month Quarter Year

Finally table will look like one shown in below image:

Page 4: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP8: we are done with report Groups. You can Preview the report:

STEP9: Format Groups: This is the final step. Without formatting the tabular data look meaningless and its very difficult to understand the report. You can do following formatting to make it easier to understand:

Group Left Indent BackgroundColorYear 2pt #7c73c8Quarter 12pt #9894caMonth 22pt #b4b4c8Date 32pt #c7c7d8SalesRegion 42pt #dadaebSalesCountry 52pt #e7e7f0ProductName 62pt #f4f4fcCustomerName(detail row) 72pt White

Toggle Groups:Select Quarter Group and click on Group Properties. Select Visibility in Group Properties and select Hideoption button. Check Dispaly can be toggled by this report item  check box and select Year from combo box.

Page 5: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Similar way toggle other report items.Also Toggle Order Number column with Particular text box.

Now click on Preview and generate the report:

Thats all about Report Groups...Cheers!!!

Conditional Formatting in SSRS 2008 Posted: Sat, 04 Sep 2010 07:29:00 +0000Alternate Background Color in Tabular Report:Alternate background color of rows in a table make it easier to read

Page 6: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

horizontally. Also it makes report look and feel better. This is very common but simple task to achieve in SSRS report using expression.

Select the detail row of the data table in the layout tab.

Go to property window and select expression of BackgroundColor and enter below expression:=IIF(RowNumber(Nothing) Mod 2 = 0,"Transparent","#cdfcbe")

Now click and Preview the report:

Format Phone number using REGEX function:Suppose you want to display Phone no in (ddd) ddd-dddd format instead of ddd-ddd-dddd. To do this, Right click on the required textbox --> click expression... and enter below expression:

=System.Text.RegularExpressions.Regex.Replace(Fields!Phone.Value, "(\d{3})[ -.]*(\d{3})[ -.]*(\d{4})", "($1) $2-$3")

Now click on Preview and see the report: 

  Changing Font Color dynamically:

Page 7: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Sometime we need to format data based on the their values. Below is an example for Base rate color selection:

Base Rate Color<= 15  Green> 15 AND <=25  Blue> 25 AND <=40  Black> 40  Red

To do this, Enter C (Currency format) in Format and below expression in Color property of BaseRate field:=SWITCH(Fields!BaseRate.Value <= 15,"Green",

Fields!BaseRate.Value <= 25,"Blue",Fields!BaseRate.Value <= 40,"Black",Fields!BaseRate.Value > 40,"Red")

Now click on Preview and see the report:

Swapping Font Color and BackgroundColor:Suppose you want to swap Font Color and BackgroundColor of Gender field. Use below expressions in BackgroundColor and Color properties respectively:

=IIF(Fields!Gender.Value = "M","Tomato","Teal")

=IIF(Fields!Gender.Value <> "M","Tomato","Teal")

Now click on Preview and see the report:

Page 8: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

SSRS Expressions Posted: Thu, 02 Sep 2010 00:07:00 +0000Reporting Services ExpressionsIn Reporting Services, Expressions are used frequently in reports to control content and report appearance. Expressions are used throughout the report definition to specify or calculate values for parameters, queries, filters, report item properties, group and sort definitions, text box properties, bookmarks, document maps, dynamic page header and footer content, images, and dynamic data source definitions. 

Expressions begin with an equal (=) and are written in Visual Basic. Expressions can include a combination of constants, operators, and references to built-in values (fields, collections, and functions), and to external or custom code. Expressions can be one of the following two types:

Simple - An expression that is a single reference to an item in a built-in collection, such as, a dataset field, a parameter, or a built-in field. Simple expressions appear on the design surface and in dialog boxes in brackets, such as [FieldName], which represents the underlying expression=Fields!FieldName.Value. You can type simple expressions directly into a text box on the design surface and the corresponding expression text is set as the value of a placeholder inside the text box.

Page 9: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Complex - An expression that includes more than a simple reference. Complex expressions appear on the design surface as <>. You can create complex expressions in the Expression dialog box or type them directly into the Property pane.

Examples of SSRS Expression

Using Built-in FieldsDisplay  Report Execution Time in a textbox:="Report Execution Time: " & Globals!ExecutionTime

Display Page No in a textbox:="Page " & Globals!PageNumber & " of " & Globals!TotalPages

Similar way you can use other built-in Fields in expressions e.g. Report Folder, Report Name, ReportServerUrl, UserID, Language etc. as shown below:

Date & Time FunctionsThe Today() function provides the current date. The expression  =Today() can be used in a text box to display the date on the report, or in a parameter to filter data based on the current date. This function will return date in M/d/yyyy 12:00:00 AM format. You can use Format function to display required format. Some of the popular date formats are given below:

Page 10: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Expression Output=FORMAT(Today(),"M/d/yy") 8/23/10=FORMAT(Today(),"MM-dd-yyyy") 08-23-2010=FORMAT(Today(),"MMM-dd-yyyy") Aug-23-2010=FORMAT(Today(),"MMMM dd, yyyy") August 23, 2010=FORMAT(DateField,"MMM dd, yyyy hh:mm:ss")

Aug 23, 2010 01:43:33

=FORMAT(DateField,"MMM dd, yyyy HH:mm:ss")

Aug 23, 2010 13:43:33

=FORMAT(DateField,"MMM dd, yyyy HH:mm:ss.fff")

Aug 23, 2010 13:43:33.587

=FORMAT(DateField,"MMM dd, yyyy hh:mm:ss tt")

Aug 23, 2010 01:43:33 PM

Note: FormatDateTime function can also be used to format the date field e.g. =FormatDateTime(Fields!BirthDate.Value, DateFormat.ShortDate)

DateAdd - Returns a Date value containing a date and time value to which a specified time interval has been added. this function can be used in an expression to add/substract time(day, month, year, sec etc.) from given date field: =DateAdd(DateInterval.Month, 6, Parameters!StartDate.Value) 

DateDiff - Returns a Long value specifying the number of time intervals between two Date values. =DateDiff("yyyy",Fields!BirthDate.Value,Today())

DatePart - Returns an Integer value containing the specified component of a given Date value. =DatePart("q",Fields!BirthDate.Value,0,0)

=DatePart(DateInterval.Quarter,Fields!BirthDate.Value, FirstDayOfWeek.System, FirstWeekOfYear.System)

Page 11: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

There are many other Date &Time functions which can be used expression:

String Functions• Combine more than one field by using concatenation operators and Visual Basic constants. The following expression returns two fields, each on a separate line in the same text box:=Fields!FirstName.Value & vbCrLf & Fields!LastName.Value

•Format dates and numbers in a string with the Format function.=Format(Parameters!StartDate.Value, "M/D") & " through " & Format(Parameters!EndDate.Value, "M/D")

•The Right, Len, and InStr functions are useful for returning a substring, for example, trimming DOMAIN\username to just the user name. The following expression returns the part of the string to the right of a backslash (\) character from a parameter named User:=Right(Parameters!User.Value, Len(Parameters!User.Value) - InStr(Parameters!User.Value, "\"))

The following expression results in the same value as the previous one, using members of the .NET Framework System.String class instead of Visual Basic functions: =User!UserID.Substring(User!UserID.IndexOf("\")+1, User!UserID.Length-User!UserID.IndexOf("\")-1)

• Join - Display the selected values from a multivalue parameter=Join(Parameters!MyParameter.Value,",")

Page 12: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

•The Regex functions from the .NET Framework System.Text.RegularExpressions are useful for changing the format of existing strings, for example, formatting a telephone number. The following expression uses the Replace function to change the format of a ten-digit telephone number in a field from "nnn-nnn-nnnn" to "(nnn) nnn-nnnn": =System.Text.RegularExpressions.Regex.Replace(Fields!Phone.Value, "(\d{3})[ -.]*(\d{3})[ -.]*(\d{4})", "($1) $2-$3")

There are many other function which can be used in expression as shown below:

Conversion Functions

You can use Visual Basic functions to convert a field from the one data type to a different data type.

The following expression converts the constant 100 to type Decimal in order to compare it to a Transact-SQL money data type in the Value field for a filter expression: =CDec(100)

Page 13: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

The following expression displays the number of values selected for the multivalue parameter MyParameter: =CStr(Parameters!MyParameter.Count) 

Decision Functions

The IIF function returns one of two values depending on whether the expression is true or false. The following expression uses the iif function to return a Boolean value of True if the value of Total exceeds 100. Otherwise it returns False:=IIF(Fields!Total.Value > 100, True, False)

Use multiple IIF functions (nested IIFs) to return one of three values depending on the value of PercentComplete. The following expression can be placed in the fill color of a text box to change the background color depending on the value in the text box. =IIF(Fields!PercentComplete.Value >= 10, "Green", IIF(Fields!PercentComplete.Value >= 1, "Blue", "Red"))

A different way to get the same functionality uses the Switch function. The Switch function is useful when you have three or more conditions to test. The Switch function returns the value associated with the first expression in a series that evaluates to true: =Switch(Fields!PercentComplete.Value >= 10, "Green", Fields!PercentComplete.Value > 1,"Blue", Fields!PercentComplete.Value = 1, "Yellow", Fields!PercentComplete.Value <= 0,"Red",)

A third way to get the same functionality uses the Choose function. The Choose function uses the first parameter as an index to one of the remaining function parameters. The first parameter must be an integer. If the background color of a text box in a table is set to this expression, the value of MyIndex controls the color. =Choose(Fields!MyIndex.Value,"Red","Green","Yellow")

Page 14: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Check the value of the PurchaseDate field and return "Red" if it is more than a week old, and "Blue" otherwise. This expression can be used to control the Color property of a text box in a report item:=IIF(DateDiff("d",Fields!PurchaseDate.Value, Now())>7,"Red","Blue") 

Recursive Hierarchy Group in SSRS 2008 Posted: Wed, 25 Aug 2010 23:29:00 +0000In this article, I am going to explain how to create a Recursive Hierarchy Group in SSRS 2008 to display hierarchical levels. This is helpful when we want to display hierarchical data in a report e.g. employees in an organizational chart as shown below: 

Pre-requisites for this article:

11 SQL Server 2008 along with SSRS installed11 Business Intelligence Development Studio (BIDS)11 AdventureWorksDW2008R2 database. Click here to install this

database from codeplex.11 Familier with SSRS

Below are the stpes to create Recursive Hierarchy Group:STEP 1: To begin, create new report in your existing solution. Add new Shared Data Source. If you don't know how to create a shared data source, click Creating Shared Data Source in SSRS 2008.

 

Page 15: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 2: Create a new dataset for the report. Just right click on the data source and click Add Dataset... to create new data set as shown below:

In Dataset Properties window, enter dsMain in Name textbox and below T-SQL code in Query textbox:SELECT [EmployeeKey],[ParentEmployeeKey,[FirstName] + ' ' + ISNULL([MiddleName],'') + ' ' + [LastName] EmployeeName],[Title]FROM [AdventureWorksDW2008R2].[dbo].[DimEmployee]  Finally click OK to close the window and save changes. The Report Data will look like below image:

STEP 3: Drag and drop Table control and map with dsMain dataset. Select EmployeeName in first column,Title in second column and =Level() expression in the third column. Set following properties for table control:

Header Background color = DarkBlue Header Color = White

Page 16: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Font = Verdana, 8pt

STEP 4:  Set Group Properties to reference Recursive Parent. Select table control --> click View and checkGrouping as shown below:

Open Row Group properties, click on add button and select [EmployeeKey] in Group on box. 

Click on Advance tab of Group Properties window and select [ParentEmployeeKey] in Recursive parentbox. Click OK and save changes. STEP 5: We are done with report development. Click on Preview to generate the report. You can see a report like one shown below:

Page 17: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Here, you can see the Employee Hierarchy but not as per standard. We need to format the text to make it better report. Do below formating for EmployeeName textbox:1) Enter below expression in FontWeight under Font Property:=IIF(Count(Fields!EmployeeName.Value, "Details", Recursive) > 1, "Bold", "Normal")

2)  Enter below expression in LeftIndent under Indent Property:=CStr(2 + (Level()*20)) + "pt"

Again Preview the report, report will look like below image:

Cheers!!!

Pulling SharePoint List using SSIS 2008 Posted: Mon, 23 Aug 2010 23:18:00 +0000Do you want to pull SharePoint List data into SQL database using SSIS? If your answer is Yes then you can go for SharePoint List Source. You can download the setup from Microsoft SQL Server

Page 18: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Community Sample: Integration Services: here is the link: SharePointListAdaptersSetup

This component has two controls - SharePoint List Source and SharePoint List Destination. The Specific Features of the included SSIS Components are:

SharePoint Source Component

Auto-detects all of the public fields from a SharePoint List or view of the list.

Supports removal of fields from the output flow, which optimizes the query against SharePoint for increased performance.

Supports restricting SharePoint data by a custom CAML query, which can be provided through a variable expression for fine tuned filtering over large lists.

Provides a tuning feature for the # of rows to return at a time. Often with SharePoint, large lists need to be brought over in smaller batches than wide (many field) lists, or else the Webservice will die.

SharePoint Destination Component

Auto-detects all of the editable fields from a SharePoint List

Only fields bound to columns from the input flow will be ‘updated’, for performance.

Supports deleting rows by ID

System Requirements .Net 3.5 Framework SQL Server Integration Services 2008

 How to Use

Page 19: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Download the sample from SharePointListAdaptersSetup

Run SharePointListAdaptersSetup.msi to install the SSIS component. This installer places pre-built binaries into the Global Assembly Cache (GAC) and into the C:\Program Files\Microsoft SQL Server\100\DTS\PipelineComponents directory (if present).

A good way to explore the sample is to try using it, understand its behavior, and then begin reviewing the source code for the component. If you do not see the SharePoint adapters in your toolbox automatically, then follow these instructions:

Open Business Intelligence Development Studio, open a package, and then click Choose Toolbox Items on the Tools menu.

In the Choose Toolbox Items dialog box, click the SSIS Data Flow Items tab, and then checkSharePoint Destination and SharePoint Source.

Click Ok. The SharePoint source and destination components

should now appear in the toolbox for the data flow task. You can add the source and destination components to the data flow of the package.

Dynamic SSIS Package to Import Excel files into SQL Server Database Posted: Thu, 12 Aug 2010 07:38:00 +0000Problem/ScenarioNeed to import Excel files to a SQL table. Everyday one file is created at specified location in the source system. We need to copy that file from Source System to Local system and then load to SQL Table.

Conditions:1.  Each file should be loaded only once. Everynight Job should be executed to load data into reporting Data mart.2.  Source system will maintain all the history files so files at souce

Page 20: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

should not be deleted.3.  If Job failed due to some reason (schema changes, server down, connection issues etc.), it should load all the files from last run date to current date in next successul run. For example, job didn't run last one week then whenever job runs next time successfully, it should load current file as well as all the files of last week which were missing.4.  All the source files will have the same structure (Schema)5.  Nomenclature - Each file will have name Transaction followed by current date in YYYY-MM-DD format. For example, if a file was created on 01-Aug-2010 then its name should be Transaction2010-08-01.

SolutionI will take advantage of the ForEach Loop Container. I'll create a new SSIS package to solve the above problem.

STEP 1:Create following tables in your local database (destination database).CREATE TABLE [TransactionHistory](   [TransactionID] [int] NOT NULL,   [ProductID] [int] NOT NULL,   [ReferenceOrderID] [int] NOT NULL,   [TransactionDate] [datetime] NOT NULL,   [TransactionType] [nchar](1) NOT NULL,   [Quantity] [int] NOT NULL,   [ActualCost] [money] NOT NULL,   CONSTRAINT [PK_TransactionHistory_TransactionID]    PRIMARY KEY CLUSTERED ([TransactionID] ASC)) ON [PRIMARY]GO

CREATE TABLE [ExcelFilesLog](   [FileName] [varchar](100),   [FileCreatedDate] [datetime],   [FileLoadDate] [datetime],   [RecordCount] [int],) ON [PRIMARY]GO

Page 21: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 2: Create a new SSIS package and rename it to LoadDynamicExcelFiles.dtsx

STEP 3: Add following package variables:

VariableName Description ExamleLastRunDate To store last run date  2010-07-30CurrentDate To hold running date  2010-08-10DirectorySource

To store source directory path D:\SSIS\Hari\SourceFiles

DirectoryDestination

To store localdirectory path D:\SSIS\Hari\DestinationFiles

CurrentFileName

To store currentfile name

D:\SSIS\Hari\SourceFiles\Transaction2010-08-01

Create one OLE DB connection (I will use (local).TestHN connection manager) for local database where you want to load excel files data. Create one Excel Connection Manager for excel files located in D:\SSIS\Hari\DestinationFiles. At least one file should be there to create excel connection manager.

Click on Excel Connection Manager --> go to Properties window --> Select Expression and set ExcelFilePathwith package variable User::CurrentFileName as shown below:

Page 22: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

For this article, I'll use two directories - one for sources files and one for destination files. Location of these files are given below:Source Files: D:\SSIS\Hari\SourceFilesDestination Files: D:\SSIS\Hari\DestinationFiles

I have created few excel files from Production.TransactionHistory table of AdventureWorks2008R2database as shown below:

I have created files from 2010-07-20 to 2010-08-01. After executing the package first time, I will create files from 2010-08-02 to 2010-08-09 to test the package.

STEP 4:Drag and drop File System Task and double click to open File System Task Editor. Enter FST - Delete destination directory

Page 23: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

content in name and  select Delete directory content as Operation. Set IsSourcePathVariable to True and select SourceVariable as User::DirectoryDestination. Finally click on OK and save changes.

Drag and drop Execute SQL Task and double click to open Execute SQL Task Editor. Enter Execute SQL Task - Get LastRunDate in Name, select Single row as Result Set, Conection Type as OLE DB and Connection as (local).TestHN and SQLSourceType as Direct input. Enter below query in SQLStatement:SELECT ISNULL(MAX([FileCreatedDate]),'2010-01-01') AS LastRunDateFROM [dbo].[ExcelFilesLog] (NOLOCK)

In Result Set tab, set Result Name 0 to variable User::LastRunDate.Finally click OK and save changes.

Drag and drop Script Task and double click to open Script Task Editor. Select User::DirectoryDestination, User::DirectorySource,

Page 24: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

User::LastRunDate in ReadOnlyVariables. Click on Edit Script... and paste below code:

using System.IO; 

public void Main(){   try   {      string DirectorySource = Dts.Variables["User::DirectorySource"].Value.ToString();      string DirectoryDestination = Dts.Variables["User::DirectoryDestination"].Value.ToString();      DateTime LastRunDate = (DateTime)Dts.Variables["User::LastRunDate"].Value;

      string fileName,fileExtension;      string[] files = Directory.GetFiles(DirectorySource);      //Copy source files to destination      foreach (string f in files)      {         fileName = Path.GetFileName(f);         fileExtension = Path.GetExtension(f);         DateTime CurrentDate = DateTime.Parse(fileName.Substring("Transaction".Length, 10));

         if ((DateTime.Compare(CurrentDate,LastRunDate)>0) && (fileExtension == ".xlsx"))        {            //MessageBox.Show(fileName.ToString());            File.Copy(f, Path.Combine(DirectoryDestination, fileName), true);

Page 25: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

         }       }      Dts.TaskResult = (int)ScriptResults.Success;   }   catch (Exception ex)   {      Dts.Log(ex.Message, 0, null);      Dts.TaskResult = (int)ScriptResults.Failure;   }}

Drag and drop Foreach Loop container. Select Foreach File Enumerator as Enumerator, enterD:\SSIS\Hari\DestinationFiles in Folder path and *.xlsx in files textbox. Select Fully qualified as Retrieve file name. In Variable Mappings, Select User::CurrentFileName for Index 0 to store current file name for each iteration.

Now drag and drop Data Flow Task inside Foreach loop container. Use Excel Source reader to read excel files from destination directory. Use Excel Connection Manager as connection manager for excel files. In connection properties, Select @[User::CurrentFileName] as ExcelFilePath. Use Data Conversion, if required. Use Row Count Task to count number of

Page 26: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

rows in data flow and store it in User::RecordCountvariable. Use OLE DB Destination to load data into SQL table.

Drag and drop Execute SQL Task inside Foreach loop container to log information about current file.

Double click on Execute SQL Task to open Execute SQL Task Editor, enter Execute SQL Task - Insert info into Log table as Name, None as Result Set, OLE DB as connection type, (local).TestHN as connection,Direct input as SQLSourceType and below query as SQLStatement.

DECLARE

@FileName varchar(500)

,@FilePath varchar(500)

,@DestinationPath varchar(500)

SET @DestinationPath = ?

Page 27: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

SET @FilePath = ?SET @FileName = REPLACE(@FilePath,@DestinationPath + '\','')

INSERT INTO [ExcelFilesLog](   [FileName]   ,[FileCreatedDate]   ,[FileLoadDate]   ,[RecordCount])SELECT @FileName [FileName],CAST(SUBSTRING(@FileName,12,10) as datetime) [FileCreatedDate],GETDATE() [FileLoadDate],?

In Parameter mapping,  map User::DirectoryDestination, User::CurrentFileName, and User::RecordCount with parameter 0,1,2 respectively as shown below.

Finally click OK and save changes.

Below is the final layout of our package: 

Page 28: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 6:We are done with the package development. To execute the package, go to SSIS package location, (in this example, it is D:\SSIS\Hari\Sample\SSIS-Sample1), right click on LoadDynamicExcelFiles.dtsx --> Open with --> SQL Server 2008 Integration Services Package Execution Utility. This will open Execute Package Utility. Click on Execute button to run ssis package. Now you can see the progress of package execution in Package Execution Progress window.

Page 29: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Now you can check ExcelFileLog table to cross check the result of package.

Now I'll add few more excel files in source location - from

Transaction2010-08-02 to Transaction2010-08-09 as shown below:

Page 31: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Posted: Sat, 07 Aug 2010 07:35:00 +0000Cascading parameters provide a way of managing large amounts of report data. You can define a set of related parameters so that the list of values for one parameter depends on the value chosen in another parameter. For example, the first parameter is independent and might present a list of product categories. When the user selects a category, the second parameter is dependent on the value of the first parameter. Its values are updated with a list of subcategories within the chosen category. When the user views the report, the values for both the category and subcategory parameters are used to filter report data. 

In this post we will walk through the steps of building a report and with query parameters for both product category and subcategory items. Then we will develop individual datasets to provide values for the cascading parameters.I will use AdventureWorks2008R2 database for this article. You can install this database from codeplex.

STEP 1:Open your existing Report Server project or create a new Report Server project. Add a new report and rename it as CascadingParameters.rdl. Now create a Data Source for AdventureWorksDW2008R2 database. For more information about creating shared Data Source, Click Creating Shared Data Source in SSRS 2008.

STEP 2:Create three data sets as mentioned below:

1. dsProductCategory: This Data Set will be used to create a parameter for Product Categories. Use below query for this data set:SELECT ProductCategoryID,Name AS ProductCategoryFROM Production.ProductCategory (NOLOCK)ORDER BY Name

Page 32: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

 2. dsProductSubcategory: This Data Set will be used to create a Cascading Parameter for Product Subcategories. Use below stored procedure for this data set.

CREATE PROC procProductSubcategory(   @ProductCategoryID varchar(1000))ASBEGIN   SELECT ProductSubcategoryID,Name AS ProductSubcategory   FROM Production.ProductSubcategory (NOLOCK)   WHERE ProductCategoryID IN (SELECT Value    FROM [dbo].[SplitMultivaluedString](@ProductCategoryID,','))   ORDER BY NameEND-------- UNIT TESTING -------------------- EXEC procProductSubcategory '1'-- EXEC procProductSubcategory '1,2'-- EXEC procProductSubcategory '1,3'----------------------------------------GO

Note: Function SplitMultivaluedString is used to split comma seperated values of parameter @ProductCategoryID. Click Function to Split Multi-valued Parameters to get T-SQL script of this function.

Result of EXEC procProductSubcategory '1,3' is shown below:

Page 33: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

3. dsProduct: This data set will give the list of all the products based on the Product SubCategories selected at run time. Use below stored procedure for this data set:

CREATE PROC procProductsList(   @ProductSubcategoryID varchar(1000))ASBEGIN   SET NOCOUNT ON

   SELECT      PC.Name ProductCategory      ,PS.Name ProductSubcategory      ,P.Name ProductName,ProductNumber      ,Color,Size,[Weight]   FROM Production.Product P (NOLOCK)   INNER JOIN Production.ProductSubcategory PS     ON PS.ProductSubcategoryID = P.ProductSubcategoryID    INNER JOIN Production.ProductCategory PC      ON PC.ProductCategoryID = PS.ProductCategoryID    WHERE P.ProductSubcategoryID IN (SELECT Value     FROM [dbo].[SplitMultivaluedString](@ProductSubcategoryID,','))END

Page 34: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

-- EXEC procProductsList '6,7,8,18,30,36'GO

Result of EXEC procProductsList '6,7,8,18,30,36' is shown below:

STEP 3:Once you create above data sets, you can see two parameters created automatically - ProductCategoryIDand ProductSubcategoryID as shown below:

Now double click on parameter ProductCategoryID to open Report Parameter Properties window. InGeneral, change the Prompt value as Product Category and check Allow multiple values checkbox. InAvailable Values, Select Get values from a query option and select dsProductCategory in Dataset,ProductCategoryID in Value

Page 35: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

field and ProductCategory in Label field. Now click on Default Values, Click on Get values from a query option and select dsProductCategory in Dataset, ProductCategoryID in Value field. Finally click OK to save changes.

Similarily change the properties of parameter ProductSubcategoryID. In General, change the Prompt value as Product Subcategory and check Allow multiple values checkbox. In Available Values, Select Get values from a query option and select dsProductSubcategory in Dataset, ProductSubcategoryID inValue field and ProductSubcategory in Label field. In Default Values, Click on Get values from a queryoption and select dsProductSubcategory in Dataset, ProductSubcategoryID in Value field.

Finally click OK to save changes.

STEP 4:

In report Design, drag and drop a table control and map with dsProduct data set. select all the columns from dsProduct in the tables and format this as shown below:

Thats all. We are done with a report having one cascading parameter. Click on Preview to view the report. Now you can see that values of Parameter Product Subcategory depends on the parameter Product Category. By Default, Product Category parameter has (Selected All) so Product Subcategory will also display all the values.

Page 36: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Values of Product Subcategory parameter will be filtered as per selection of the values of Product Category parameter, which will filter the actual report data because Product Subcategory parameter is used to filter report data.

Function to convert a string in Camel Case (Proper Case) Posted: Wed, 04 Aug 2010 22:08:00 +0000Sometime, we need to display string data in proper case, i.e. first character of each word should be in UPPER case. SQL Server doesn't provide any built-in function for this requirement. In this article, I am putting T-SQL code to create this function. This is a generalised Function that will return any input string in Proper Case

Page 37: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

[Camel Case]. Means Afetr every space, first later will be in UPPER case.

Example:Input String    :  'microSoft sql server'Output String : 'Microsoft Sql Server'  /************************************************* CREATED BY : HARI SHARMA ON MAR 30, 2007PURPOSE : TO CONVERT INPUT STRING IN CAMEL CASE**************************************************/CREATE FUNCTION [dbo].[CamelCase](@Str varchar(8000))RETURNS varchar(8000) ASBEGIN  DECLARE @Result varchar(2000)  SET @Str = LOWER(@Str) + ' '  SET @Result = ''  WHILE 1=1  BEGIN    IF PATINDEX('% %',@Str) = 0 BREAK    SET @Result = @Result + UPPER(Left(@Str,1))+    SubString  (@Str,2,CharIndex(' ',@Str)-1)    SET @Str = SubString(@Str,      CharIndex(' ',@Str)+1,Len(@Str))  END  SET @Result = Left(@Result,Len(@Result))  RETURN @ResultEND----------------------------------------------------- HOW TO USE ---- SELECT dbo.CamelCase('hARi nARAyan shARMa')-- Output: Hari Narayan Sharma---------------------------------------------------GO

Creating First Cube in SSAS 2008 Posted: Sun, 01 Aug 2010 20:34:00 +0000

Page 38: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Nowadays, analytical solutions are becoming mission critical for many organizations. Microsoft SQL Server 2008 Analysis Services (SSAS) is designed to provide exceptional performance and scalable support with millions of records and thousands of users from different locations.

Why to Build a Cube?There are many advantages of cube over relational data mart.

While querying a data mart, you can get most of the results but not everything you need for business analysis and decsion making. Cube can help you to get answers of all "What-If" scenarios.

Building a cube helps to house your data to centralize the business rules for calculations that you can't easily store in a relational data mart.

The structure of the cube makes it much easier to write queries to compare data year over year (YOY), or to create cumulative values such as year-to-date (YTD) sales.

Scalable Infrastructure - Analysis Services can scale to support databases of many terabytes in size with many thousands of users.

Superior Performance - Analysis Services cubes are multidimensional structures that enable fast access to high volumes of pre-aggregated data, empowering end users to gain insight into relevant business data at the speed of thought.

You gain the ability to manage aggregated data in the cube. To improve query performance in a relational data mart, we often create summary tables to prepare data for queries that don't require transaction-level detail. SSAS creates the logical equivalent of summary tables (called aggregations) and keeps them up-to-date.

I would like to introduce beginners to Microsoft SQL Server Analysis Services (SSAS) by creating a simple cube from AdventureWorksDW2008R2. You can install this database from codeplex.I'll cover following things in this article:

Page 39: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

11 Creating Analysis Services Project11 Creating Data Source11 Creating Data Source View11 Creating Cube and Dimensions11 Creating Dimension Hierarchies11 Deploying Cube Database from BIDS

Creating Analysis Services Project.First step is to create a project in Business Intelligence Development Studio (BIDS). Launch BIDS from Start --> All Programs --> Microsoft SQL Server 2008 --> SQL Server Business Intelligence Development Studio and then click File --> New --> Project. In the New Project dialog box, select Analysis Services Project. In the Name text box, type LearnSSAS and, if you like, change the location for your project. I'll store this project at locationD:\Hari. Click OK to create the project.

 Creating Data SourceNow add a data source to define the connection string for data mart AdventureWorksDW2008R2. In Solution Explorer, right-click the Data Sources folder and click New Data Source.

Page 40: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

In the Data Source Wizard, click Next on the Welcome to the Data Source Wizard page if it hasn't been disabled. On the Select how to define the connection page, click New to set up a new connection. In theConnection Manager, the default provider is the Native OLE DB\SQL Server Native Client 10.0, which is correct for our project.To define the connection, type the name of your server in the Server Name text box. Alternatively you can select it from the drop-down list, then select AdventureWorksDW2008R2 in the database drop-down list and click Test Connection button to check the connection. Finally click on OK as shown below: 

When you're back in the Data Source Wizard, click Next. On the Impersonation Information page, select Use the service account option so that service account will be used to read data from the source when loading data into your SSAS database and service

Page 41: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

account  must have read permissions to do so. Click Next and thenFinish to complete the wizard. Creating Data Source ViewNow next step is to create a data source view (DSV) from the data source to define dimensions and cubes. You can make changes to the DSV without modifying the actual data source, which is very useful if you have only read permissions to the data mart. In Solution Explorer, right-click on the Data Source Views folder and then click New Data Source Views...You can see Data Source View Wizard. Click Next on the Welcome page. On the Select a Data Source page, select the data source just added to the project (Adventure Works DW2008R2.ds) and click Next. Now add required objects to the DSV by double-clicking each table or view onSelect Tables and Views page. I want to add the following tables to the DSV to make it easy to understand for beginners:DimDate, DimProduct, DimProductCategory, DimProductSubcategory, and FactInternetSales. You can always add more tables later if you want to explore advance BI questions. Now click Next in the Data Source View Wizard once you are finished adding required tables followed by click on Finish. You can give a name to your DSV before clicking Finish button.I would recommend you to change the name of objects by selecting each one in the DSV designer and remove the Dim and Fact prefixes from the FriendlyName property because when you create dimensions and cubes, only FriendlyName property will be assigned to the objects.The DSV is shown below:

 Creating Cube and DimensionsNext step is to create a Cube and Dimensions from the data source view. In Solution Explorer, right-click on the Cubes folder and then

Page 42: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

click New Cube...You can see Cube Wizard. Click on Next in Welcome to the Cube Wizard page.On the Select Creation Method page, keep the default option Use existing tables and click Nextbutton. On the Select Measure Group Tables page, choose InternetSales table and click Next.

Now the wizard displays all the measures available in the selected measure group tables. Measures are basically numeric values e.g. OrderQuantity, Unit Price, Sales Amount, Tax Amount etc. Select only the following measures from Internet Sales Group: Order Quantity, Unit Price, Total Product Cost, Sales Amount, and Internet Sales Count

Now click on Next button to open Select New Dimensions page and select Date and Product dimensions. ClickNext to proceed.

Page 43: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

In the Completing the Wizard page, enter the cube name as AdventureWorksCube and click Finish button to complete the wizard. Cube layout is shown below:

Now click on each dimensions and add required attributes from the Data Source View.Date Dimension:Drag and drop FullDateAlternateKey, CalendarYear, CalendarQuarter, EnglishMonthName, and EnglishDayNameOfWeek. Rename FullDateAlternateKey with Full Date, EnglishMonthName with Calendar Month, and EnglishDayNameOfWeek with Calendar Week as shown below:

Page 44: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Product Dimension:Drag and drop EnglishProductCategoryName from ProductCategory table, EnglishProductSubcategoryName from ProductSubcategory table and Color, ModelName, Size and Weight from Product table.

Creating Dimension HierarchiesNavigate to Date Dimension Structure. Drag and drop Calendar Year attribute into Hierarchies surface area following by Calendar Quarter, Calendar Month, Calendar Week , and Full Date attributes.Rename hierarchy with Calendar. You'll see a warning mark in the hierarchy because attribute relationship is not set properly.

Set Attribute RelationshipsClick on the Attribute Relationships tab in the dimension designer. This tab is available only in Analysis Services 2008. By default, all attributes relate directly to the key attribute, Date Key as shown below:

To optimize the design by reassigning relationships, Right Click on Full Date and select New Attribute Relationship. Select Related Attribute as Calendar Week and Relationship type as Rigid (will

Page 45: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

not change over time). Repeat same thing for remaining attributes. Finally Attribute Relation will look like below image:

Deploying Cube Database from BIDSNow its time to deploy the cube at required server. Right click on the project (LearnSSAS in this example) and click properties to open project properties page. Enter Server Name name Server property and Database name in Database property as shown below:

Click OK to save changes. Now right click on the project and click on Process to Build and Deploy the project. You will a message while deploying the database first time.

Click on Yes to proceed. Now you can see Process Database - PreojectName window. Click on Run to continue.

Page 46: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Once the database is deployed and processed successfully, you can see the data through Browser tab or directly through SQL Server Analysis Services. You can also pull cube data in Excel using Excel OLAP Pivot Tables, which is the prefered option used by business managers.

Send Mail Task in SSIS 2008 Posted: Mon, 26 Jul 2010 17:38:00 +0000How to send a notification/mail to specific group of peoples through SSIS packages? Thanks to Send Mail Task. This can be achieved easily using send mail task.By using the Send Mail task, a package can send messages if tasks in the package workflow succeed or fail, or send messages in response to an event that the package raises at run time. For example, the task can notify a database administrator about the success or failure of the Backup Database task.

You can configure the Send Mail task in the following ways:

Write the message text for the e-mail. Write a subject line for the e-mail message. Set the priority level of the message. The task supports

three priority levels: normal, low, and high.

Page 47: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Specify the recipients on the To, Cc, and Bcc lines. If the task specifies multiple recipients, they are separated by semicolons.

I'll explain this by an example:

STEP 1:Create a new SSIS Package and rename it with SendMailTask.dtsx.

STEP 2:Add two package variable MessageSource and SMTPServer of type string to this package as shown below:

STEP 3:Add a new SMTP Connection manager and configure its properties. Enter SMTP Connection manager in Name andConnection for sending mails inDescription boxes. Now enter your SMTPServerName in SMTP server box as shown below:

Page 48: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Set SmtpServer property of above connection manager with variableUser::SMTPServer by clicking on Expression in properties of SMTP Connection Manager. This is highlighted in below snap shot:

STEP 4:Drag and drop Script Task to set your message. Double click on Script Task to open Script Task Editor, Select User::MessageSource as ReadWriteVariables and click on Edit Script... button to set the message. Write below code in main function. (This is for VB.NET, you can choose C# or VB.NET)

Public Sub Main()   'Set MessageSource variable   Dts.Variables("User::MessageSource").Value = "Hi," & vbCrLf & _   "This is a test mail to check Send Mail Task in SSIS!" & vbCrLf & vbCrLf & _   "Thanks and Regards," & vbCrLf & "_____________" & vbCrLf & "Hari"   Dts.TaskResult = ScriptResults.SuccessEnd Sub  However, the message text can be a string that you provide, a connection to a file that contains the text, or the name of a variable (in our case) that contains the text. 

Page 49: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

  STEP 5: Drag and drop Send Mail Task and double click on it to open Send Mail Task Editor. Select Mail from Left side and set mail properties as shown below: 

  Thats all. We are done with Send Mail Task setup, this package will look like below snapshot. Just right click on package in Solution Explorer and Execute. Receiver will get an email as soon as package executes successfully. However, mail delivery depends on the response of SMTP Server as well.   

            

Page 50: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

      Note: 

11 The To, Cc, and Bcc lines are limited to 256 characters.11 The SMTP connection manager supports only

anonymous authentication and Windows Authentication.

Find Largest Size Tables in a Database Posted: Sat, 24 Jul 2010 05:30:00 +0000Below is the stored procedure to return largest tables of a database.

IF OBJECT_ID('sp_LargestTables' ,'P') IS NOT NULLDROP PROC sp_LargestTablesGO/***************************************************************CREATE BY : Hari SharmaPURPOSE : To get a list of tables according to their size.***************************************************************/CREATE PROC sp_LargestTables(   @n int = NULL,   @IsSystemAllowed bit = 0)ASBEGIN   SET NOCOUNT ON   DECLARE @LOW int   SELECT @LOW = LOW    FROM [master].[dbo].[spt_values] (NOLOCK)    WHERE [number] = 1 AND [type] = 'E'

   IF @n > 0 SET ROWCOUNT @n

Page 51: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

   SELECT TableName,[Row Count],[Size (KB)] FROM    (      SELECT QUOTENAME(USER_NAME(o.uid)) + '.' +                      QUOTENAME(OBJECT_NAME(i.id))          AS TableName         ,SUM(i.rowcnt) [Row Count]         ,CONVERT(numeric(15,2),           (((CONVERT(numeric(15,2),SUM(i.reserved)) * @LOW) / 1024.0))) AS [Size (KB)]      FROM sysindexes i (NOLOCK)      INNER JOIN sysobjects o (NOLOCK)          ON i.id = o.id AND          ((@IsSystemAllowed = 1 AND o.type IN ('U', 'S')) OR o.type = 'U')       WHERE indid IN (0, 1, 255)      GROUP BY          QUOTENAME(USER_NAME(o.uid)) + '.' +          QUOTENAME(OBJECT_NAME(i.id))   ) AS Z   ORDER BY [Size (KB)] DESC

   SET ROWCOUNT 0ENDGO

How to use:

1. If you want all the user tables in the database with largest db size then:EXEC sp_LargestTables [No Need to pass parameters]

2. If you want only 3 tables in the database with largest db size then:EXEC sp_LargestTables 3

3. If you want only 20 tables in the database with largest db size including system tables then:EXEC sp_LargestTables 20,1

Page 52: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Function to Split Multi-valued Parameters Posted: Wed, 21 Jul 2010 22:00:00 +0000How to split a comma seperated value?Many times we need to write T-SQL statements to split a comma seperated value, however string is not necessarily to be comma seperated, it can be seperated by any delimiter e.g. comma (,), @, &, ; etc.

How to use Multi-valued Parameters of SSRS report in a Stored procedures?One more question comes around, how to use a multi valued parameter of SSRS report in a Stored Procedure to filter report data? I am sure you can't use a multi valued parameter directly in T-SQL code without spliting multiple values, if you do so without spliting values, SPROC will throw an error.

To find the answer of above questions, you create a user defined function using below T-SQL code:

/********************************************** CREATED BY HARI PURPOSE : To split any multivalued string seperated by any delimiter into multiple rows***********************************************/ CREATE FUNCTION [dbo].[SplitMultivaluedString] (    @DelimittedString [varchar](max),    @Delimiter [varchar](1) ) RETURNS @Table Table (Value [varchar](100)) BEGIN    DECLARE @sTemp [varchar](max)    SET @sTemp = ISNULL(@DelimittedString,'')                 + @Delimiter    WHILE LEN(@sTemp) > 0    BEGIN       INSERT INTO @Table 

Page 53: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

      SELECT SubString(@sTemp,1,             CharIndex(@Delimiter,@sTemp)-1)             SET @sTemp = RIGHT(@sTemp,        LEN(@sTemp)-CharIndex(@Delimiter,@sTemp))    END    RETURN END GO 

/* How to use this function:-----------------------------------------SELECT * FROM [dbo].[SplitMultivaluedString] ('1,2,3,4', ',') SELECT * FROM [dbo].[SplitMultivaluedString] ('1;2;3;4', ';')SELECT * FROM [dbo].[SplitMultivaluedString] ('Hari#Thomas','#')*/

Sequence Container in SSIS - Different ways of using Sequence Containers Posted: Tue, 20 Jul 2010 00:32:00 +0000Integration Services includes the Sequence container, which makes it simple to divide the control flow in a package into groups of tasks and containers that you can manage as a unit.Using Sequence containers lets you handle the control flow in a package in more detail, without having to manage individual tasks and containers.If a package has many tasks, it can be helpful to group the tasks in Sequence containers.

I'll explain different scenarios where Sequence Container paly an important role to implement business rules.

Scenario 1:

Page 54: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Sequence Task SC1 must execute first. SC1 may have many task with or without precedence constraints. The group of these task must execute prior to any other tasks in the package.

Sequence Task SC2 must start after completion of SC1. SC2 must execute irrespective of Failure/Success of SC1.

Sequence Task SC3 contains Maintenence Plan Tasks and should be followed by SC2. SC3 must execute only after successfully execution of

SC2. 

Page 55: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Scenario 2:

Sequence Task SC1 must execute first. Sequence Task SC2 must start based on logical

condition. This condition can be based on package variables.  Sequence Task SC3 contains Maintenence Plan Tasks

and should be followed by both SC1 and SC2. SC3 must execute after successfully execution of SC1. SC3 should execute regardless of SC2 but if SC2 executes, SC3 must execute after SC2.

  Scenario 3: This is real scenario in many BI applications. 

SC1 must execute prior to other task. This Sequence Container may contain many tasks to pull data from hetrogenious data sources.

SC2 should be followed by SC1. This can be used to Insert/Update dimension tables and fact tables along with

Page 56: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

intermediate tables (if any). This container may further contain Sub - Sequence Containers e.g. SC2(a) to handle dimension Insert/Update and SC2(b) to update Intermediate and Fact tables.

SC3 should be followed by SC2. This may contains SSAS Tasks to Build/Prcoess Cubes. This container may also have Sub - Sequence Containers e.g. SC3(a) to check whether Current Month partition exists or not. If Yes than Do Nothing Else Create Current Month Partitions using Script task. SC3(b) can be used to Process Dimensions and Current Month Partitions.

SC4 can be used for Maintenence Plan tasks. If SC3 successfully completed (Evolution operation - Expression and Constraint) than take Backup of Cube, Shrink Datamart and Take Backup of Datamart.

SC5 can be used for Recovery Paln. If SC3 fails, Restore Cube from previos & Latest Backup available.. 

Page 57: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

However, there are many more ways of utilizing Sequence Containers. Further, things depends on complexity of business requirement rules defined.

Report Parameters in SSRS 2008 Posted: Sun, 18 Jul 2010 07:24:00 +0000What is Report Parameters in SSRS?In SSRS, parameters are used to specify the data to use in a report, narrow down your report data for better analysis, connect related reports together, and vary report presentation. Report parameters can be Single-Valued and Multivalued.

Using Parameters in Reporting Services:The most common use of parameters is to vary report data retrieved by dataset queries. In this scenario, users are prompted for a value or values when they run the report, and the dataset query retrieves only the data that is requested. You can change the report parameter properties in the report design tools to include a valid values list that displays at run time.

You can also create cascading parameters, which retrieve hierarchical data from a data source. I'll explain cascading parameters in my nect post. First I want to explain creating a report parameter in SSRS 2008.

Below are the uses of report parameters:

To Control Report Data - by selecting required parameters values to filter the report data.

To Control Report Appearance - use parameters to change report appearance using expression-based properties, including conditionally hiding report items and conditionally changing text color.

Page 58: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

To Connect to Other Reports - use parameters to link to drillthrough reports, subreports, and linked reports.

To Select Specific Data Columns - parameters can be used to select specific columns of a table/matrix at run time.

How to create Report Parameters:Query parameters are added to a dataset query by way of the query designers or the Dataset Properties dialog box. After you create a query with parameters, Reporting Services automatically links query parameters to report parameters with the same name. Below are the steps to create parameters:

STEP 1:To begin, start a new Report Server Project project in Visual Studio 2008 by clicking on Start --> All Programs --> SQL Server 2008 --> SQL Server Business Intelligence Development Studio. Then, from the menu, select File --> New --> Project to open New Project wizard. Now select Report Server Project from Visual studio installed templates and specify Name, Location and Solution Name. 

I'll use the solution ctreated in my previous article. I'll use FirstReport.rdl for this example and I'll create a parameter Designation to filter report data for selected designations.

STEP 2:Create a new Data Set for the report parameter. I will add a dataset dsDesignation for Employee's Designation using query SELECT DISTINCT Desg AS Designation FROM Employee as shown below:

Page 59: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 3:Now I will add a parameter Designation. In Report Data section, right click on Parameters node and clickAdd Parameter... as shown below:

Page 61: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 4:In Report Parameter Properties window, enter Name and Prompt of the parameter and select the Data type from dropdown box. For our example, enter Designation in Name and Prompt text boxes and selectText as data type.

Page 62: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 4: Now click on Avaliable Values to set available values for the parameter. Select Get values from a query. Select dsDesignation as Dataset, Designation as Value field and Label field.

Page 63: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 5: Click on Default Values, SelectGet values from a query. Select dsDesignation as Dataset, Designation as Value field. Click OK to save changes.

STEP 6:

Page 64: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Double click on your main dataset (dsMain) to open Dataset Properties. Now Select  Parameters and click on Add button to map Designation parameter. 

STEP 7:Now final step, just add parameter in your query as shown in below snapshot:WHERE [Desg] = @Designation

Page 65: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Now preview the report to check the action of parameter used:

Note: This article describes onlu about single valued parameter. I'll explain multi-valued parameter in my next article.

First Report in SSRS 2008 Posted: Tue, 13 Jul 2010 18:52:00 +0000

Page 66: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

In this article, I will explain how to create a simple report (that could be first report for a newbie) using SSRS 2008. Here I am assuming that you have successfully installed SQL Server 2008 along with SSRS.

There are two ways to create Reports in SSRS. You can develop the report manually, or you can use the Report Wizard to give yourself a head start. For this first report, I am going to take advantage of the wizard.

STEP 1:To begin, start a new Business Intelligence project in Visual Studio 2008 by clicking on Start --> All Programs --> SQL Server 2008 --> SQL Server Business Intelligence Development Studio. Then, from the menu, selectFile --> New --> Project to open New Project wizard. Now select Report Server Project from Visual studio installed templates and specify Name, Location and Solution Name. I am specifying theseReportProjectSSRS, D:\Hari, and ReportProjectSSRS respectively as shown below:

Page 67: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 2:In Solution Explorer, right click on Reports folder and select Add

New Report.  This will open Report Wizard. Click Next on the Welcome screen and this will bring you to the Select the Data Source screen.

STEP 3:Enter the name of Data Source as dsLocal and select type as Microsoft SQL Server. Now click on Edit button to set the connecting string for data source, this will open Connection Properties window. Enter Server name and database name and click onTest Connection buttion to make sure the connection is established. Click OK button twice to close Test Results and Conection Properties windows.

Page 69: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

You can check the Make this a shared data sourcecheckbox to make this data source as shared so that it can be used for other reports as well. Now click onNext to proceed.

Page 70: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 4:This will open Design the Query wizard. Here you can define your Query string. Alternatively you can use Query Builder... to build your query. I will use below query to pull data from Employee table:

SELECT   [Emp_code],[Emp_Name],[Desg],   [Head],[DOB],[Basic],[Dept_Code] FROM Employee (NOLOCK)  Click Next to proceed. It will display Select the Report Type wizard. Select Tabular option and click Next to proceed.   STEP 5: Now you can see Design the Table wizard. Select required fields from Available fields and clicked on details button to make these fields available in details part of a report. You can do data grouping as well usingGroup button. Click Next to proceed.

Page 71: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

STEP 6:Now you can see Choose the Table Style wizard. Select default style Slate and click Next. Finally you can see Completing the Wizard. Enter report name FirstReport and click Finish to complete the wizard.

Page 73: Groups in SSRS 2008files.learnmsbieasily.webnode.in/200000929-4406d44f… · Web viewProvides a tuning feature for the # of rows to return at a time. Often with SharePoint, large

Thats all. We are done with our First report in SSRS 2008. Report at design time will look like one shown below:

Click on Preview to generate the report: