SSRS avoid WHERE clause if select all is selected - sql-server

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

Related

Need to Add Values to Certain Items

I have a table that I need to add the same values to a whole bunch of items
(in a nut shell if the item doesn't have a UNIT of "CTN" I want to add the same values i have listed to them all)
I thought the following would work but it doesn't :(
Any idea what i am doing wrong ?
INSERT INTO ICUNIT
(UNIT,AUDTDATE,AUDTTIME,AUDTUSER,AUDTORG,CONVERSION)
VALUES ('CTN','20220509','22513927','ADMIN','AU','1')
WHERE ITEMNO In '0','etc','etc','etc'
If I understand correctly you might want to use INSERT INTO ... SELECT from original table with your condition.
INSERT INTO ICUNIT (UNIT,AUDTDATE,AUDTTIME,AUDTUSER,AUDTORG,CONVERSION)
SELECT 'CTN','20220509','22513927','ADMIN','AU','1'
FROM ICUNIT
WHERE ITEMNO In ('0','etc','etc','etc')
The query you needs starts by selecting the filtered items. So it seems something like below is your starting point
select <?> from dbo.ICUNIT as icu where icu.UNIT <> 'CTN' order by ...;
Notice the use of schema name, terminators, and table aliases - all best practices. I will guess that a given "item" can have multiple rows in this table so long as ICUNIT is unique within ITEMNO. Correct? If so, the above query won't work. So let's try slightly more complicated filtering.
select distinct icu.ITEMNO
from dbo.ICUNIT as icu
where not exists (select * from dbo.ICUNIT as ctns
where ctns.ITEMNO = icu.ITEMNO -- correlating the subquery
and ctns.UNIT = 'CTN')
order by ...;
There are other ways to do that above but that is one common way. That query will produce a resultset of all ITEMNO values in your table that do not already have a row where UNIT is "CTN". If you need to filter that for specific ITEMNO values you simply adjust the WHERE clause. If that works correctly, you can use that with your insert statement to then insert the desired rows.
insert into dbo.ICUNIT (...)
select distinct icu.ITEMNO, 'CTN', '20220509', '22513927', 'ADMIN', 'AU', '1'
from ...
;

How to merge columns in SQL of the same table

I have two date columns.
Sometimes they both have dates(Which will be same always in both the columns) and sometimes one is empty and one has date value.
So, instead of two columns, I am trying to get one column.
If one is empty it will take date value from other column and if both have values(which will always be same) it will just take any of the value from the two columns.
I have tried UNION commands but its not giving me the desired result.
SQL Server has a couple different options for this scenario. You can use COALESCE, ISNULL, or a CASE statement.
Based on the information you provided I would use COALESCE. It offers several benefits over ISNULL and is very simple to implement. A CASE statement seems like overkill for what you are trying to do. Check out the link above for more info on each solution.
Welcome to Stack Overflow!
You need Coalesce
Also, in the future, you should put sample data and metadata in text in your question, rather than as attachments.
You could use the ISNULL statement if it is SQL
SELECT ISNULL(ReturnDate,RepartureDate) as dateAct FROM AviationReservation_dev
UPDATE tableName
SET Date1Column = ISNULL(Date1Column, Date2Column);
Context: ISNULL ( check_expression , replacement_value ), if first argument is not null, it will use that argument.
After the update, delete the other column.
It seems there is no case for both column to be empty, then in such condition, you can do something like this:
SELECT
CASE
WHEN column1 IS NULL THEN column2
WHEN column2 IS NULL THEN column1
ELSE column1 orcolumn2

Convert SSRS parameter to Null

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'.

Update a view doesn't work

I'm working on a view which is then updated by the user. This update basically changes the value of column. But right now it doesnt let me do that and produces this :
Update or insert of view or function '' failed because it contains a derived or constant field.
I know this is because I have a constant in the select statement but is there a way to get around it? Please help
This is my code for the view
Create view Schema.View1
as
SELECT
Convert(Varchar(20),l.jtpName) as JobType, Convert(Varchar(10),' <All> ')as SubCategory , Convert(varchar (3), Case when a.jtpName= l.jtpName and a.subName= ' <All> ' then 'Yes' else 'No' end) As AutoProcess from Schema.JobType l left join Schema.Table1 a on l.jtpName=a.jtpName
UNION
SELECT
Convert(Varchar(20),a.jtpName) as JobType, Convert(Varchar(10),a.subName) as SubCategory, Convert(varchar (3),Case when b.jtpName= a.jtpName and b.subName= a.subName then 'Yes' else 'No' end) As AutoProcess from Schema.SubCategory a left join fds.Table1 b on a.subName=b.subName
GO
Finally the update statement:
UPDATE Schema.View1 SET AUTOPROCESS = Case WHEN AUTOPROCESS = 'Yes' Then 'No' END Where JOBTYPE = 'Transport' and SUBCATEGORY= 'Cargo'
Thank You
You cannot update a column that is the result of a computation.
According to MSDN, one of the conditions for a view column to be updatable is this:
Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
The columns being modified in the view must directly reference the underlying data in the table columns. The columns cannot be derived in any other way, such as through the following:
An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, and VARP.
A computation. The column cannot be computed from an expression that uses other columns. Columns that are formed by using the set operators UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a computation and are also not updatable.
The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT clauses.
TOP is not used anywhere in the select_statement of the view together with the WITH CHECK OPTION clause.
Here not only does your view uses the UNION statement, the AutoProcess field you are trying to update is actually the result of a CASE statement that uses two fields. It makes no sense to try and update that.
I would recommend that you use stored proc to perform writing operations. Or, as Damien suggest, you could use an INSTEAD OF trigger on the view too.
You have to create a TRIGGER and manually apply the changes from the inserted and deleted pseudo-tables against the base tables yourself.
There is no way for sql server to work backwards from your convert functions to the original fields. You cannot update a view this way.
If the view contained your jptName and subName fields, you might be able to update just those fields.

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