Convert SSRS parameter to Null - sql-server

I have SSRS report that showing Marketing Features. we have in the MF a field called "Test", the values are "PSI 1" or PSI 2" and also the field can be empty.
I added a dataset for the Test parameter with this query:
SELECT DISTINCT Corp_Test
FROM [Tfs_Warehouse].[dbo].[CurrentWorkItemView]
WHERE ProjectNodeGUID = #ProjectGuid
AND System_WorkItemType = 'Marketing Feature'
UNION
SELECT 'Null'
ORDER BY Corp_Test
Now in the report, the values are PSI 1 PSI 2 and Null:
In the Main Query I filtered the results according to the parameter like this:
where COALESCE(Corp_Test, 'Null') IN (#TestParam)
The report works fine, and if I selected all values I get also Marketing Features with empty Test field.
My question is:
Instead of Null on the dropdown, I want it to be written No PSI and actually in the main query it will be Null. is it possible?

In your parameter properties, on the Available Values screen you will see an option for the Value and the Label. This allows you to show one thing to the end user (eg: user friendly description) whilst passing another (eg: key value) to the report.
In your dataset for the test parameter add a column to hold the Label of the value you want to pass through to the query. This can be the same as your Value if you so wish, but gives you the flexibility you require on the Null entry:
SELECT DISTINCT Corp_Test as Value
,Corp_Test as Label
FROM [Tfs_Warehouse].[dbo].[CurrentWorkItemView]
WHERE ProjectNodeGUID = #ProjectGuid
AND System_WorkItemType = 'Marketing Feature'
UNION ALL -- As you have DISTINCT above, UNION ALL will work faster and give the same results as UNION (which removes duplicates)
SELECT 'Null' as Value
,'No PSI' as Label
ORDER BY Corp_Test
Once you have done this, change your parameter to use the Value field as the parameter value and the Label field as the label shown to the user.

SELECT
ISNULL(Corp_Test,'No PSI') AS Corp_Test
FROM
(SELECT DISTINCT Corp_Test
FROM [Tfs_Warehouse].[dbo].[CurrentWorkItemView]
WHERE ProjectNodeGUID = #ProjectGuid
AND System_WorkItemType = 'Marketing Feature'
UNION
SELECT 'Null'
) AS Corp
ORDER BY ISNULL(Corp_Test,'No PSI')
Remember to implement the change in your where clause main query. By main query, I mean the query that is feeding your report

The simple and easiest way is what #sgeddes answered in his comment.
I just repleced the where COALESCE(Corp_Test, 'Null') IN (#TestParam) with where COALESCE(Corp_Test, 'No PSI') IN (#TestParam), and in the dataset I replaced the SELECT 'Null' with SELECT 'No PSI'.

Related

SSRS multiple single cells

I am trying to figure out best way to add multiple fields to a SSRS report.
Report has some plots and tablix which are populated from queries but now I have been asked to add a table with ~20 values. The problem is that I need to have them in a specific order/layout (that I cannot obtain by sorting) and they might need to have a description added above which will be static text (not from the DB).
I would like to avoid situation where I keep 20 copy of the same query which returns single cell where the only difference would be in:
WHERE myTable.partID = xxxx
Any chance I could keep a single query which takes that string like a parameter which I could specify somehow via expression or by any other means?
Not a classical SSRS parameter as I need a different one for each cell...
Or will I need to create 20 queries to fetch all those single values and then put them as separate textfields on the report?
When I've done this in the past, I build a single query that gets all the data I need with some kind of key.
For example I might have a list of captions and values, one per row, that I need to display as part of a report page. The dataset query might look something like ...
DECLARE #t TABLE(Key varchar(20), Amount float, Caption varchar(100))
INSERT INTO #t
SELECT 'TotalSales', SUM(Amount), NULL AS Amount FROM myTable WHERE CountryID = #CountryID
UNION
SELECT 'Currency', NULL, CurrencyCode FROM myCurrencyTable WHERE CountryID = #CountryID
UNION
SELECT 'Population', Population, NULL FROM myPopualtionTable WHERE CountryID = #CountryID
SELECT * FROM #t
The resulting dataset would look like this.
Key Amount Caption
'TotalSales' 12345 NULL
'Currency' NULL 'GBP'
'Population' 62.3 NULL
Lets say we call this dataset dsStuff then in each cell/textbox the xpression would simply be something like.
=LOOKUP("Population", Fields!Key.Value, Fields!Amount.Value, "dsStuff")
or
=LOOKUP("Currency", Fields!Key.Value, Fields!Caption.Value, "dsStuff")

Manually enter a parameter value or All by default in SSRS

I'm trying to create a parameter in SSRS where the user has the option to either manually enter an id or else have the report return all records. This is how the parameter currently looks:
In this situation the user can manually enter one providerid, which works. But is it possible for the user to leave the providerid parameter blank and then by default the report will run for all records?
The providerid parameter is populated with a stored procedure:
Select distinct cast(providerid as varchar(25)) as providerid
from Table A
I've read other threads on here that appear similar, but I can't figure out how to get this work.
The standard way to do this is:
Add another item to your drop list called ALL with a special value
Select distinct
cast(providerid as varchar(25)) as providerid,
cast(providerid as varchar(25)) as providerLabel
from Table A
union all
select -1, 'All Providers'
Make sure you assign label and value correctly.
Allow for this special value in your stored proc:
where ...
and (providerid = #providerid or #providerid = -1)
and ...

SSRS avoid WHERE clause if select all is selected

I am working on an SSRS report and a part of my sql query is like
WHERE SuperVisorId IN (#SupervisorIDs) AND CreatedDate> #StartDate
where the #SupervisorIDs is a dropdown with option of "select all" and individual supervisors.
So if the supervisors "all" option is selected , then I don't need to include that in the where clause and my where clause is only this
WHERE CreatedDate> #StartDate
So how can I make the WHERE clause looks different according to Selection of dropdown?
This only applies if you are using a single valued parameter with a manually added All option to the list of available values. Multi-value parameters do not know when all options are selected.
SQL Server doesn't always execute the conditions in a where clause in the order you write them, so if you are using where (#p = 'all' or col = #p) and ... you may still be comparing your values.
If performance is a concern, you can avoid this by using a short circuiting case, that only progresses to the actual data comparison if it is necessary:
where case when #SupervisorIDs = 'All' then 1
else case when SuperVisorId = #SupervisorIDs then 1
else 0
end
end = 1
and CreatedDate > #StartDate
Assuming that you are using a dataset query to populate the supervisor parameter dropdown, then you can try this.
Create an additional hidden parameter of a boolean type. For this example, I'll call it #AllSupsSelected. Set the default value of the parameter to:
=COUNT(Parameters!SupervisorIds.Label)=COUNT(Fields!SupervisorIdLabel.Value,"SupervisorDataset")
Replace the field and dataset names accordingly. If the dataset is returning non-distinct values, you may have to tinker further to get this working.
Now your query can read:
WHERE #AllSupsSelected OR SupervisorId IN (#SupervisorIds)
Make your where clause like below
WHERE (
(SuperVisorId IN (#SupervisorIDs))
OR (
#SupervisorIDs = 0
AND COLUMN_WITH_NULL IS NOT NULL
)
)
AND CreatedDate > #StartDate
And pass 0 when selected "select all"
As an actual answer to your particular problem, set your multi-valued parameter dataset up similar to this to return all Supervisors as well as a value at the bottom of the list for No Supervisor:
select distinct SupervisorID as Value
,SupervisorName as Label
,1 as Sort
from Suppliers
union all
select <Uniquely identifiable value with the same data type as SupervisorID> as Value
,'No Supervisor' as Label
,2 as Sort
order by Sort
,Label
Then in your dataset set up your filtering similar to the below. I have structured it in this manner to avoid using the isnull function on your SupervisorID column, which will hurt the query performance:
select cols
from tables
where SupervisorID in(#SupervisorID)
or (SupervisorID is null
and <Unique value from above> in (#SupervisorID)
)
which version of ssrs ? in 2016, you don't need to alter your query. when you click "select all" by default it pass all the values. so your query works good without changing anything.
thanks,
SK

TSQL query to filter directory

I'm trying to create a business directory in which I'm using the following query to pull data from 2 tables that contain the business info.
select *
from BND_Listing
left join BND_ListingCategories on BND_Listing.CatID = BND_ListingCategories.CatID
order by Company asc
I have a form that has 3 dropdowns I'm using to filter the above query using "Filters" that really are just components I need to add to my query above that will listen to query string values passed in by the form.
On submit of my form I'm redirecting back to the same URL but adding the following in my URL based on values selected from 3 dropdown fields.
filter-Category=[Category]&filter-City=[City]&filter-State=[State]
I've got this working correctly but am having difficulties when no value is passed into my URL. This happens when a user filters only by 1 of the 3 possible fields. To fix this I'm thinking I can create an "All" value that would be like filter-State=ALL
How can I update my query to pull data to listen for these filters in the query-string?
Any insight, examples really appreciated.
Hope I make sense I'm still new to programming.
The following query returns 0 results until all filters are set. If only 1 filter is set it crashed my application.
select *
from BND_Listing
where
(Category = '[querystring:filter-Category]'
or '[querystring:filter-Category]'='All')
and
(City = '[querystring:filter-City]'
or '[querystring:filter-City]'='All')
and
(State = '[querystring:filter-State]'
or '[querystring:filter-State]'='All')
UPDATE:
Thanks for all the input everyone.
I've tried this simplified query in SQL Server Management Studio to test.
SELECT *
FROM BND_listing
WHERE city = IsNull('Trinity', city)
It returns no results even though 'Trinity' is in fact a city in one of my records in the BND_Listing table.
I understand the ALL would add more filters but this basic query is still not pulling anything?
UPDATE 2:
On page load where I have not pressed the sort button and there are no query string values passed yet. If I want my grid to load ALL table records should I use a UNION command for my basic query.
select *
from BND_Listing
Plus the more complex query used for filtering the results? So far all query examples below pull in nothing from my grid because of the WHERE statement.
Are you limited to just a select query that has to be placed in the plug-in? If not, I would create a stored procedure and read up on dynamic SQL. Dynamic SQL would allow you to dynamically generate and execute a completely different query based on whatever conditions you specify. With dynamic SQL, you could also dynamically generate the entire predicate instead of having to hard code each condition.
Another (less efficient) alternative would be to use LIKE instead of = in your predicate. For example:
SELECT *
FROM BND_Listing
WHERE Category LIKE CASE
WHEN [querystring:filter-Category] = 'All' THEN '%'
ELSE '[querystring:filter-Category]'
END
AND City LIKE CASE
WHEN [querystring:filter-City] = 'All' THEN '%'
ELSE '[querystring:filter-City]'
END
AND State LIKE CASE
WHEN [querystring:filter-State] = 'All' THEN '%'
ELSE '[querystring:filter-State]'
END
Assuming you want to search for 'All' for a given category when no filter is present, you can just treat an empty filter as meaning all:
SELECT *
FROM BND_Listing
WHERE (Category = '[querystring:filter-Category]' OR
'[querystring:filter-Category]' = 'All' OR
COALESCE([querystring:filter-Category], '') = '') AND
(City = ... )
...
Perhaps you could try something like this.
SELECT *
FROM BND_listing
WHERE category = IsNull('[querystring:filter-Category]', category)
AND city = IsNull('[querystring:filter-City]', city)
AND state = IsNull('[querystring:filter-State]', state)
This functionality will check for an active filter if present and compare the appropriate field to ensure it matches.
In the case the filter has not been set it will compare the field to itself so it will always return a true result.
When you want all the records when the input is NULL then handle it using IS NULL.
SELECT *
FROM BND_listing
WHERE (category = '[querystring:filter-Category]' OR [querystring:filter-Category]' is NULL)
AND (city = '[querystring:filter-City]' OR '[querystring:filter-City]' IS NULL)
AND (state ='[querystring:filter-State]' OR '[querystring:filter-State]' IS NULL)
Note : This method will use any INDEX present on Category or city or state where as ISNULL or COALESCE method will restrict the optimizer from using INDEX

Select All as default value for Multivalue parameter

I'm building a report in Visual Studio 2008 with a lot of multivalue parameters and it's working great, but I would like to have have the "(Select all)" option as the default value when the report is opened.
Is there some kind of expression or SQL code I can use to make this happen? Or do I need to choose "(Select all)" every time, in every parameter, each time I want to run the report?
Try setting the parameters' "default value" to use the same query as the "available values". In effect it provides every single "available value" as a "default value" and the "Select All" option is automatically checked.
Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything
Create Parameter (if not automaticly created)
Define values - wrong way example
Define values - correct way example
Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.
The Result
One picture for Data type: Int
Does not work if you have nulls.
You can get around this by modifying your select statement to plop something into nulls:
phonenumber = CASE
WHEN (isnull(phonenumber, '')='') THEN '(blank)'
ELSE phonenumber
END
The accepted answer is correct, but not complete.
In order for Select All to be the default option, the Available Values dataset must contain at least 2 columns: value and label. They can return the same data, but their names have to be different. The Default Values dataset will then use value column and then Select All will be the default value. If the dataset returns only 1 column, only the last record's value will be selected in the drop down of the parameter.
Adding to the answer from E_8.
This does not work if you have empty strings.
You can get around this by modifying your select statement in SQL or modifying your query in the SSRS dataset.
Select distinct phonenumber
from YourTable
where phonenumber <> ''
Order by Phonenumber
It works better
CREATE TABLE [dbo].[T_Status](
[Status] [nvarchar](20) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'notActive')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
DECLARE #GetStatus nvarchar(20) = null
--DECLARE #GetStatus nvarchar(20) = 'Active'
SELECT [Status]
FROM [T_Status]
WHERE [Status] = CASE WHEN (isnull(#GetStatus, '')='') THEN [Status]
ELSE #GetStatus END
This is rather easy to achieve by making a dataset with a text-query like this:
SELECT 'Item1'
UNION
SELECT 'Item2'
UNION
SELECT 'Item3'
UNION
SELECT 'Item4'
UNION
SELECT 'ItemN'
The query should return all items that can be selected.

Resources