SSRS: Display field using CAST in sql - sql

I'm trying to display a value in the same field by using iif statement. But one is INT, another is Decimal and the last one is percentage. So, I CAST them as varchar in SQL. How do I display the result in SSRS field?
Here is an example:
IF #Choice = '1'
BEGIN
SELECT
UserId, CAST(IntNum AS VarChar(10)) AS Result
FROM Sample
END
ELSE IF #Choice = '2'
BEGIN
SELECT
UserId, CAST(DecNum AS VarChar(10)) AS Result
FROM Sample
END
How do I display Result in a SSRS field?

Instead of embedding the logic in your SQL statement, why not do it in the report since (presumably) this is where #Choice is defined?
SQL:
-- #Choice is not needed in this query.
SELECT UserId, IntNum, DecNum
FROM Sample
Report:
Add a Calculated Field in the field listing of your DataSet (call it Result):
=IIF(Parameters!Choice.Value = 1, Fields!IntNum.Value.ToString, Fields!DecNum.Value.ToString)
Now your report will have 4 fields in the DataSet:
UserId (int)
IntNum (int)
DecNum (dec)
Result (string)

I think it would be best to do your logic in a CASE Statement, which is really one column, so it should work well in SSRS.
SELECT UserID,
CASE
WHEN #Choice = 1 THEN CAST(IntNum AS VARCHAR(10))
WHEN #Choice = 2 THEN CAST(DecNum AS VARCHAR(10))
WHEN #Choice = 3 THEN CAST(PercentageNum AS VARCHAR(10))
END AS Result
FROM [Sample]

Related

Create Function from selection from common table expression

I need to create function from a complex query which was generating temp tables from the main table, to do subtraction in certain value based on condition. Temp tables are setone, settwo, setthree, and the main table is called main. The query is below.
with
setone
AS
(SELECT type_id
, time
, id
, type
FROM main
WHERE type = 0),
settwo
AS
(SELECT type_id
, time
, id
, type
FROM main
WHERE type = 1),
setthree
AS
(SELECT setone.*
, (SELECT max(time)
FROM settwo
WHERE settwo.id = setone.id
AND settwo.time < setone.time)
AS off
FROM setone)
SELECT id, SUM (off - time) / COUNT (*) MEAN
FROM setthree
GROUP BY id
Now, The result from the query is value called MEAN, how to create function based on this query that pass id and time then will return value MEAN.
Function will look like
dbo.[FunctionGetMEAN](id,time) as MEAN
Example of expected result:
id time mean
222 1 0.3
333 1 0.7
222 2 0.8
Ah. What you might want is a stored procedure. Look up create procedure . Basic syntax goes like this..
Create procedure dbo.procedurename
( #id int
, #time int)
As
Begin
your query here*
Where statement needs to.be included before the group by
Where
Id = #id
And time = #time
The last statement needs to be :
End
You then call yiur stored procedure like this for example.
Exec dbo.yourprocedure 1, 100

How to write an attribute name to the select query dynamically

I have a table including:
ID Name Period0Id Period1Id Period2Id
What I would like to receive data based on a user-defined parameter #check.
Lets assume:
declare #check int = 1;
In this case I need to get Period1Id value from the table. So I need to have something like that:
Select ID, Name, StatusId = Period + #check + Id -- #check is the parameter
From mytable
However, my query is not working. How can I fix this?
Your table looks like it is not in first normal form.
Instead of three columns for Period0Id to Period2Id you could have a column for PeriodIndex with values of (0,1,2) and a single column for PeriodId and then it would be just a WHERE PeriodIndex = #Check
You can't select a column using string interpolation with a variable as you are attempting. You can use dynamic SQL to create the SQL String dynamically. Or simply hardcode the options if they all have the same dataype.
Select ID,
Name,
StatusId = CASE #Check WHEN 0 THEN Period0Id
WHEN 1 THEN Period1Id
WHEN 2 THEN Period2Id
END
From mytable
Here is an alternative way that will create dynamic columns, which is essentially using your original query:
DECLARE #check VARCHAR = 1
DECLARE #sqlquery NVARCHAR(MAX)
SET #sqlquery = N'SELECT ID, Name, StatusId = Period'+#check+'Id
FROM mytable'
EXEC sp_executesql #sqlquery

How to check a comma delimited integer values by "IF" condition T-SQL?

A simple table contains the one column with integer vales.The Figure is given below.
I am using COALESCE to construct the 'numbers' by comma.
So, now there is a problem when i check a above constructed value in IF Condition like below. It shows an error for cannot convert the varchar datatype to integer.
Now how to check the constructed values in IF condition without changing a logic? I am new for T-SQL.Thank you
When you concatenate all the numbers you are converting it a string so it no longer acts like an integer. If you want to check for a value in a list, do it directly like. SQL was made to have different values in different rows and work with them that way. Try this out:
DECLARE #failIds INT = 23;
IF #failIds IN (SELECT numbers FROM model)
BEGIN
PRINT 'YES'
END
ELSE
BEGIN
PRINT 'NO'
END
Instead of the comma separated string, you should use a table variable, temp. table or just the original table. For example, something like this:
declare #Ids table (id int)
insert into #Ids
select numbers
from model
where numbers in (23,234)
declare #failIds int = 23
if (exists (select 1 from #Ids where id = #failIds)) begin
print 'Yes'
end else begin
print 'No'
end
But you could of course do this too:
if (exists (select 1 from model where numbers = #failIds)) begin
print 'Yes'
end else begin
print 'No'
end
I am very lazy to think about it, Finally i get answer like give below. Its very simple.

Use an SSRS multi-value parameter in a SQL query without using the IN operator

I have to pass multiple values (eg: Year1, year2, year3, etc.) to the same query, but I cannot use the IN condition as I'm using less than or equal to in most of the cases. Can I do this by passing multiple values through the same parameter without changing the query?
Is it possible to get multiple values from an SSRS parameter and pass them on to the query to get the output as:
Year1 Year2 Year3
Value(output) Value(output) Value(output)
You can pass the multi-value parameter as a comma separated string but your SQL query is going to need updating to handle that CSV string. In order to pass the multi-value parameter as a CSV string you would open the dataset properties and go to the parameters tab. Then set the value of your parameter to this expresssion:
=JOIN(Parameters!MultiValueYearParameter.Value,",")
This will join all of the values in the multivalue parameter together and use a comma as the delimiter. You can then process this using the split function below (or just modify it to work inline in your SQL if you either cannot or don't need to create a separate function to do this).
This blog post on a Split Function for T-SQL using FOR XML shows how to do this without using string parsing or a while loop. String parsing is prone to error and isn't scalable and while loops should just be avoided in SQL whenever possible.
Below I've modified the split function to return a table of DATE values that you can then use in an INNER JOIN to filter your query using whatever operators you like.
--this is the parameter passed from the report
--(the date strings may not be formatted this way. do not try to rely on that)
DECLARE #YearParameter VARCHAR(MAX) = '2014-01-01,2011-12-02,2015-10-22';
--use this to do the xml parsing
declare #xml xml = N'<root><r>' + replace(#YearParameter,',','</r><r>') + '</r></root>'
--create a table variable to store the date values
DECLARE #dateValues TABLE (val DATE);
--parse the xml/csv string and cast the results to a DATE and insert into the table var
INSERT INTO #dateValues
select CAST(r.value('.','varchar(max)') AS DATE) AS val
from #xml.nodes('//root/r') as records(r);
You can then use that table variable to filter your SQL query. I've given an example of how to use it below.
In the example I create a table of rows with a start and end date. Then I filter that table to show only rows where a parameter value is between the start and end date.
DECLARE #testTable TABLE (Descript VARCHAR(25), startDate DATE, endDate DATE);
INSERT INTO #testTable (Descript, startDate, endDate)
VALUES ('row1', '2014-05-01','2014-08-01'), ('row2', '2013-10-01','2014-01-10'), ('row3', '2015-10-01','2015-12-15'),('row4','2013-01-01','2015-01-01'),
--these rows won't appear in the result set
('row5','2010-01-01','2010-06-01'), ('row6','2013-12-25','2014-05-20');
-- get all rows from the test table where a selected parameter value
-- is between the start and end dates.
SELECT *
FROM #testTable AS tbl
WHERE EXISTS (
SELECT *
FROM #dateValues
WHERE val BETWEEN tbl.startDate AND tbl.endDate
);
In SSRS you can build tables and complex solutions.
In the Text Query of report builder here is an example of splitting apart a parameter to get three dates.
BEGIN
/* suppose the inbound pram is a string with 10 places per date '01/01/2010,11/12/2012,05/06/2013' */
/* you could also nip the string apart by each comma... */
DECLARE #YEAR1 DATETIME
DECLARE #YEAR2 DATETIME
DECLARE #YEAR3 DATETIME
SET #YEAR1 = CAST(SUBSTRING(#INBOUNDPARAM, 1, 10) AS DATETIME)
SET #YEAR2 = CAST(SUBSTRING(#INBOUNDPARAM, 12, 10) AS DATETIME)
SET #YEAR3 = CAST(SUBSTRING(#INBOUNDPARAM, 23, 10) AS DATETIME)
SELECT #YEAR1 AS Year1, #YEAR2 AS Year2, #YEAR3 AS Year3
END
Of course the Year of the date is just YEAR(#Year1) = 2010 for example...

Assigning Value along with Data Retrieval

Is there a way to combine assigning a value to a variable and Selecting a column in sql. I need to compute and select a column in a table based on the variable. The variable's value changes based on another column in the table.
var #BeginValue
Columns in table : ReducedBy
My initial begin value is stored in #BeginValue. The table has reducedBy which is a factor by which my begin value should be reduced. So when i select, beginvalue for the first recored would be #BeginValue and the #EndValue should be #BeginValue = #BeginValue - reducedBy. It continues like this, as many times as the number of records in my table.
Result set must be like this:
#Begin = 10
Begin End ReducedBy
10 8 2
8 6 2
6 5 1
Is there a way with which i can achieve this without using a cursor or with multiple update statements.
You can't assign in a query that returns a result set. The closest you can get is to store the result in a table variable. Then you can both do computations against that table, and return it as a result set:
-- Store results in table variable
declare #tbl table (id int, col1 int, ...)
insert #tbl
(id, col1, ...)
select id
, col1
, ...
from ... your query here ...
-- Assign variable
select #YourVariable = ... your computation here ...
from #tbl
-- Return result set
select *
from #tbl
If your question is
Can I do..
SELECT #a = field, field2 from table
and get a resultset and set the value of #a?
Then the answer is no, not in a single statement.