Search This Blog

Tuesday, 2 October 2012

Passing a Multi value TSQL Parameter to MDX Report

I am assuming that you are familiar with the basic report design, So in below post, I am going to give details regarding the use multi value parameter only.
I have shared .RDL with respect to this post Download

Steps to pass multivalue parameter to MDX SSRS report
1.    Create your basic report with MDX query.
2.    I am using Adventure works DW cube as datasource to describe the below steps.
3.    Go to the .rdl code and write your code between <CommandText> your MDX Query </CommandText> tag.
<CommandText>= "Select {"+
"[Measures].[Average Unit Price],[Measures].[Order Quantity],[Measures].[Total Product Cost]"+
"} on columns ,"+
"Nonempty ([Sales Territory].[Sales Territory Country].[Sales Territory Country],[Measures].[Internet Order Count])*"+
"Nonempty( [Sales Territory].[Sales Territory].[Region],[Measures].[Internet Order Count])*"+
"Nonempty( [Product].[Product].[Product],[Measures].[Internet Order Count])"+
"on rows from"+
"(SELECT({[Sales Territory].[Sales Territory].[Region].&amp;["+Replace(Join(Parameters!SalesRegion.Value,"],")+"]",",",",[Sales Territory].[Sales Territory].[Region].&amp;[")+"})on columns "+
" from [Adventure Works])"</CommandText>
Change the higlighed expression as per your requirement for parameter passing 
4.    If you are using expression based query, in that case report designer will not add required parameter list automatically. You need to add it manually. In our example, the parameter list will like below image.



Let’s describe above picture.
Parameter
1.    SaleRegion is parameter we have used in our MDX .(1)
2.    Product parameter which is taking TSQL query to pass the parameter value to our MDX.  (2)
3.    Go to the parameter properties and  Allow multiple value
Data sources
4.    MultiVlaue associated with Cube (3)
5.    SQL associated with TSQL. (4)
Data Set
6.    Multivalue to MDX (5)
7.    SQL Value is for  TSQL (6)

 SQL Value query I have used is
SELECT DISTINCT SalesTerritoryAlternateKey, SalesTerritoryRegion
FROM            DimSalesTerritory
you go to the product parameter (1) and map the query value to this parameter.
1. Choose to set the Available Values.
2. Specify Dataset from value is coming
3. Choose the value that we are going to pass our MDX
4. Specify the label name.
5. Now preview your report.
 


Sunday, 30 September 2012

Efficient way of using ALL as a parameter value in multivalued parameter

Most of the time, we came into a situation where we need to pass ALL values of a multivalued parameter to our stored procedure/T-Sql and generally we pass it as a comma separated value to our query. But passing a long set of values to our SP/T-Sql under IN(..,..,..) clause decreases the performance of the query because in this case query engine needs to look into all set of available values in IN(..,..,..) clause against every record. Let’s see step by step that how we can overcome from this issue.
Step 1: Add a Select statement like below in your dataset query that you are using for the parameter binding.
Select -1 as Employee_ID,'ALL' as Employee_Name /*Change the field names as per your requirement*/
Union All
<Your T-Sql Statement>
Here we are passing -1 as a value for ALL. You can choose any other value as per your requirement but do not use NULL. Because if there will be NULL in the multivalued parameter list, you will experience an error in 2008 or below versions whereas R2 will exclude NULL records from the parameter list. This SSRS behavior makes sense because if we concatenate any value(s) with NULL, resultant will be NULL.

In support of this step, you can refer “Employee_Parameter” dataset in attached sample.
Step 2: Pass the selected multivalued parameter in your details dataset’s parameter like following expression =IIF(Parameters!Employee_ID.Value(0)=-1,Nothing,Join(Parameters!Employee_ID.Value,","))
In support of this step, you can refer the expression of the @Employee_ID parameter in “Details_Dataset” dataset in attached sample.
Step 3: Now you need to modify the <where> - clause of your resultant query in such a way that will maximize the response time of your output query like following where condition.
Select <Columns List>
From
<Tables with required joins>
Where
( (@Employee_ID IS NULL) OR (Employee_ID in (<Multivalued parameter values in comma seperated form>)) )

In support of this step, you can refer the where clause of the Details_Dataset” dataset in attached sample


You can download the sample report from following link.
You need to only modify the datasource of the sample report.

Remarks
If you are using this concept in your report, you need to convey your end user that they will see all the possible records on the report if they select other available values with ALL.

ERROR: An item with the same key has already been added

During the process of creating Multi value report. I received the following error while previewing the report
“An item with the same key has already been added.”.















I got irritate when fetch the report MDX through Sql server profiler it ran with no error. After doing lot of research my friend gave a hint (he was having the same problem using TSQL Stored procedure) and resolved my issue. The issue was due to I  added the two fields with same name .
Quick Solution
1.    Go to the report query, stored procedure and identify the duplicate fields and remove it.
2.     If the report is using MDX go to the .rdl code and identify the duplicate fields and remove it.
3.    In MDX report if the field name is different but Unique name is same as highlighted in red below than we can also experience this error
<Field Name="Average_Unit_Price">
<DataField>&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;Field xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="Measure" UniqueName="[Measures].[Average Unit Price]" /&gt;</DataField>
<rd:UserDefined>true</rd:UserDefined>
</Field>
<Field Name="Average_Unit_Price">
<DataField>&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;Field xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="Measure" UniqueName="[Measures].[Average Unit Price]" /&gt;</DataField>
<rd:UserDefined>true</rd:UserDefined>
</Field>



Saturday, 29 September 2012

Execute MDX Query with TSQL

To start with execution of MDX query with TSQL first we need to create a Linked Server. Let’s discuss few points regarding this
Linked Server
  Linked server enables the SQL Server Database Engine to execute commands against OLE DB data sources outside of the instance of SQL Server. Linked servers are configured to enable the Database Engine to execute a Transact-SQL statement that includes tables in another instance of SQL Server, or another database product such as Oracle, mysql, MS Analysis services etc. Many types of OLE DB data sources can be configured as linked server.
Now let’s proceed with creation of linked server within the sqlserver instance
Create a linked server
·         To create a linked sever you must have admin right of SqlServer.
·         Navigate to Server Objects > Linked Servers
·         Right click on Linked Servers and select New Linked Server.
Let’s take a sample cube database AdventureWorksDW2008R2 and create a linked server on this.

EXEC
sp_addlinkedserver
@server='Test', /* Here specify a name to linked server */
@srvproduct='',/*Is the product name of the OLE DB data source to add as a linked server. product_name is nvarchar(128), with a default of NULL.*/
@provider='MSOLAP',/*Is the unique programmatic identifier (PROGID) of the OLE DB provider corresponding to this data source. provider_name must be unique for the specified OLE DB provider installed on the current computer.*/
@datasrc='localhost',/*'DRIVER={SQL Server};Server=(local); Initial Catalog=master;Integrated Security=SSPI;'*/
       @catalog='Adventure Works DW 2008R2' /*Cube Database Name*/
4.       Once the linked server is set, we need TSQL Rowset OPENQUERY function.
Open Query

Executes the specified pass-through query on the specified linked server. This server is an OLE DB data source. OPENQUERY can be referenced in the FROM clause of a query as if it were a table name. OPENQUERY can also be referenced as the target table of an INSERT, UPDATE, or DELETE statement. This is subject to the capabilities of the OLE DB provider. Although the query may return multiple result sets, OPENQUERY returns only the first one.

Syntax: - OPENQUERY (linked_server,’query’)
Now you can write your Script
USE
AdventureWorksDW2008R2
GO
Declare @MDXExpression as Varchar(MAX)

Create Table  #temp(
                        Country varchar(Max),
                        Sale_Amount  float,
                        Product_cost float,
                        Tax_amount Float,
                        TProduct_Cost Float
                        )

Set  @MDXExpression =
'SELECT
NON EMPTY
      {
      [Measures].[Sales Amount]
      ,[Measures].[Standard Product Cost]
      ,[Measures].[Tax Amount]
      ,[Measures].[Total Product Cost]
      } ON 0,
NON EMPTY
      {
NonEmpty ( [Sales Territory].[Sales Territory Region].[Sales Territory Region])

      } ON 1
FROM
      [Adventure Works]';     

insert into #temp     
Exec ('SELECT * FROM OpenQuery(Test,''' + @MDXExpression + ''')')

/* Here you can join your MDX result set with your respective Sql server database tables and can extract expected result set */

SELECT      SalesTerritoryGroup,  #temp.*
FROM         DimSalesTerritory inner join #temp   on #temp.[Country]= DimSalesTerritory.SalesTerritoryCountry

Friday, 28 September 2012

#ERROR/NAN / error: Input string was not in a correct format issue in SSRS

While working on reports, we usually get “#ERROR”,”N/A” or “error: Input string was not in a correct format”error.
The major problem behind these issues is data type mismatches and some additional reasons that cause these issues.
Let’s talk about how to resolve these issues and why we get these issues.
1.    If you are performing any aggregate operation like SUM, AVG etc  on the report and also you know that your input field might have string value then never use an expression like
=sum(iif(isnumeric(Fields!YourFieldName.Value), cdbl(Fields!YourFieldName.Value),0))
OR
=sum(iif(isnumeric(Fields!YourFieldName.Value), cint(Fields!YourFieldName.Value),0))
OR
=sum(iif(isnumeric(Fields!YourFieldName.Value), iif(isnumeric(Fields!YourFieldName.Value),cdbl(Fields!YourFieldName.Value),0),0))

The reason behind this is ISNUMERIC() method works in a mysterious way. If we will try to explorer this method a bit more in detail then we will find that is ISNUMERIC()returns true for any expression if there will be any possibility to convert the expression in numeric. For example, if you test ISNumeric("1,234.55") will return true whereas SUM("1,234.55")will give you #Error. To resolve this sitution

Always use expression like =SUM(VAL(Fields!YourFieldName.Value))

2.    If you are using cube/MDX report and also using your aggregate expression like above but still getting an error or an unexpected result then you need to check these points
·         Start your sql server profiler (Tools menu-> Sql Server Profiler) with Analysis services as service type. Execute/Preview your report and extract/copy the MDX from the profile. Now execute this MDX on the Analysis Services query browser. Make sure that your report’s aggregate column is available in the output. If you see your column unavailable in the output then you need to play a workaround to get include your missing column in the output.
            The reason behind this missing column is if the resultant of your entire column is NULL and you are using Non empty/Nonempty then query engine exclude the column from the output to increase the query response time.

To resolve this problem, you need to add a calculate Member in your MDX query and append the expression by adding +0 at the end like :

With
Member CalculatedMember as [Measures].[Measure Name]+0

·         Sometime due to mishandling the expression in the MDX query/Calculated measure, we get “Infinity”,”N/A” or scientific numeric format like 1.00E+12 in the MDX output.

To see the expected result at report level, we need to handle these problems at MDX level by using appropriate expression/fields/methods.