Handling Multi Value Parameters in SSRS - sql-server-2008

I'm having 6 filters on my SSRS, out of which 1 is of Department. I have to select multiple departments and on the basis of these selections, Report will be generated. But I'm not getting how to make this done.
I created a stored procedure which is getting called in Reports.
ALTER PROC [dbo].[usp_getLessonLearntDetails]
#AssetID nvarchar(50),
#DepartmentID nvarchar(50),
#Category varchar(50),
#AuditType varchar(50),
#AuditStartYear nvarchar(50),
#AuditEndYear nvarchar(50)
AS
BEGIN
SELECT
ROW_NUMBER() OVER(ORDER BY AssetName ASC) AS Sno,
LLD.LessonComputedID, tbl_Asset.AssetName, AT.AuditType, SY.Year+' - '+EY.Year as 'Audit Period',
DE.DepartmentName, CT.CategoryName, LLD.Learnings,
CAST(CASE WHEN (LLD.RepeatedObservation = 1) THEN 'True' ELSE 'False' END AS varchar(10)) as RepeatedObservation,
LLD.RepeatedObservationReference, Att.Attachment
FROM tbl_LessonLearntDetails LLD INNER JOIN
tbl_Category CT ON CT.CategoryID = LLD.Title INNER JOIN
tbl_Asset ON LLD.AssetID = tbl_Asset.AssetID INNER JOIN
tbl_Department DE ON LLD.DepartmentID = DE.DepartmentID INNER JOIN
tbl_AuditType AT ON LLD.AuditTypeID = AT.AuditTypeID INNER JOIN
tbl_Attachment Att ON LLD.LessonLearntID= Att.LeassonLearntID INNER JOIN
tbl_AuditYear SY on SY.Year = LLD.AuditStartYear INNER JOIN
tbl_AuditYear EY on EY.Year = LLD.AuditEndYear
where ( (('0'=#AssetID and (1=1)) or LLD.AssetID=#AssetID) and
(('0'=#DepartmentID and (1=1)) or LLD.DepartmentID IN (#DepartmentID)) and
(('0'=#Category and (1=1)) or LLD.Title=#Category) and
(('0'=#AuditType and (1=1)) or LLD.AuditTypeID=#AuditType) and
(('0'=#AuditStartYear and (1=1)) or (LLD.AuditStartYear >= #AuditStartYear)) and
(('0'=#AuditEndYear and (1=1)) or (LLD.AuditEndYear <= #AuditEndYear))
);
END;

Using Split Function will work here. I did it.
In where condition, use split function.
(('0'=#DepartmentID AND (1=1)) OR LLD.DepartmentID IN (SELECT * FROM fnSplit(#DepartmentID,',')))
Thanks everyone for your response. Because of you guys only I will be able to get hit by an idea of Splitting.

Related

when i call stored procedure 1 i want to read specfic column regarding that and put them as input of stored procedure 2

The outer stored procedure gives me the product name and the raw material required for it and inner stored procedure gives me the quantity of stored procedure in my warehouse .(for eg: when I search for chocolate(i.e name_grey) in outer stored procedure I get columns with the raw material use to make chocolate(i.e )milk and sugar. Now I want to put milk and sugar as input of inner stored procedure. (where yarnstock1 is my inner stored procedure)
How do i do that?
I tried to call complete inner stored procedure in outer stored procedure. Here when i give input chocolate to outer stored procedure i get appropriate column details and i get detail of all raw material which i don't want.
---------------------------------whole stored procedure ---------------------
CREATE DEFINER=`root`#`localhost` PROCEDURE `finalgrey`(IN name_grey varchar(250))
BEGIN
SELECT
orderDate,
productname,
warpyarnid,
warpyarn ,
sum(warpneeded * meters_left) as warpneeded ,
weftyarnid,
weftyarn,
sum(weftneeded * meters_left) as weftneeded,
sum(order_quantity), sum(invoice_quantity), sum(meters_left)
FROM
(SELECT
s.orderDate,s.orderToDate,
s.orderid AS saudaid,
c.orderId AS challanid,
pm.productname,
qc.warpyarnid,
pwarp.productname AS warpyarn,
(warperwt / 100) AS warpneeded,
qc.weftyarnid,
pweft.productname AS weftyarn,
(weftwt / 100) AS weftneeded,
(sum(s.totalQuantity)/count(i.invoiceId)) AS order_quantity,
sum(i.totalQuantity) AS invoice_quantity,
IF(((sum(s.totalQuantity)/count(i.invoiceId)) - SUM(i.totalQuantity)) <0, "0", ((sum(s.totalQuantity)/count(i.invoiceId)) - SUM(i.totalQuantity)) ) as meters_left
FROM
sauda AS s
LEFT JOIN
challan c ON s.orderid = c.orderId
LEFT JOIN
invoice AS i ON c.challanid = i.challanid
LEFT JOIN
productmaster pm ON pm.productmasterid = s.itemId
LEFT JOIN
qualitymaster q ON q.productid = pm.productmasterid
LEFT JOIN
qualityconfig qc ON qc.qualityid = q.qualitymasterid and qc.active = 0
LEFT JOIN
productmaster pweft ON pweft.productmasterid = qc.weftyarnid
LEFT JOIN
productmaster pwarp ON pwarp.productmasterid = qc.warpyarnid
WHERE
s.active = 0 AND i.active = 0
AND c.active = 0
AND s.orderDate >= '2018-04-01' and s.orderType = 'Sales' and orderToDate >= CURDATE()
group by s.orderid ) xcx
where productname LIKE CONCAT('%', name_grey , '%')
group by productname;
call yarnstock1('');
END
---------------------------------inner stored procedure-----------------------
CREATE DEFINER=`root`#`localhost` PROCEDURE `yarnstock1`(in warp_yarn varchar(250))
BEGIN
select sum(itna_aayega) , itemId ,productmasterid,productname,sum(itna_bacha)
from
(select s.orderId,s.orderDate,s.orderToDate,s.itemId,py.purchaseyarnid, iys.inwardyarnstockid,
iys.purchaseorderid,(s.totalQuantity),sum(iys.totalkgs) as itna_aaya, pm.productmasterid,pm.productname,
CASE WHEN orderToDate<current_date() THEN "0"
WHEN orderToDate>current_date() AND s.totalQuantity < sum(iys.totalkgs) THEN "0"
ELSE s.totalQuantity - sum(iys.totalkgs) END AS itna_aayega,
if(orderToDate<current_date(),"0", (sum(iys.finalkgs) * 1)) as itna_bacha #group_concat(iys.totalkgs)
from sauda s
LEFT JOIN purchaseyarn py
ON s.orderId = py.purchaseorderid
LEFT JOIN inwardyarnstock iys
on py.purchaseyarnid = iys.purchaseyarnid
left join productmaster pm on s.itemId = pm.productmasterid
where iys.active =0 and s.active =0 and py.active = 0 and s.orderDate >= '2018-04-01' and s.type = 'yarn' and s.orderType = 'purchase'
group by s.orderId) xxx
where productname LIKE CONCAT( warp_yarn, '%')
group by itemId ;
END[]
If you want to pass / receive table structure to / from an another stored procedure, you can use a temporary table. A temporary table is visible throughout the connection and a temporary table created in a stored procedure is visible to other stored procedures within same connection.

How to implement the below query using ssis

Can we discuss how to load the below query result into a destination table ,using ssis.I know we can use this in T-sql and also as an OLEDB source query.But still wondering how to implement it ,only using data flow components
SELECT
CLIENTID = CAST(PER.CLIENTID AS INT)
,CASEID = CAST(CS.CASEID AS INT)
,CAST(RIGHT(ev.oid, 10) as int) AS EventID
,ev.ServiceSubtypeCode
,ev.ServiceSubtypeCode +' - '+ev.ServiceSubTypeDesc as ServiceSubTypeDesc
,WU.ProviderID as WorkunitProviderID
,WU.ProviderName as WorkUnitProviderName
,ev.eventstartdate as AssessmentStartDate
,CONVERT(CHAR(5),ASM.getstarttimestamp,8) as AssessmentStartTime
,ev.EVENTENDDATE as AssessmentEndDate
,ev.EVENTENDTIME as AssessmentEndTime
,CAST(asm.getAssmtTemplateName as nvarchar(200)) as AssessmentTypeDesc
,j.providerid
,j.ProviderName
,j.ProviderRole
,EV.ISCOMPLETED
, EV.ISFINALISED
,EV.ISREVOKED
, EV.REVOKEDDATE AS REVOKEDDATE
,ASM.OID AS ASSESSMENTID
FROM DBO.ASSESSMENT ASM
LEFT OUTER JOIN DBO.INDIVIDUALPERSON PER ON ASM.MYPERSON = PER.OID
LEFT OUTER JOIN DBO.[CASE] CS ON ASM.MYCASE = CS.OID
LEFT OUTER JOIN (
SELECT CAST(ST.CODE AS VARCHAR(8))AS SERVICETYPECODE
, CAST(ST.DESCRIPTION AS VARCHAR(100)) AS SERVICETYPEDESC
, CAST(SST.CODE AS VARCHAR(8)) AS SERVICESUBTYPECODE
, CAST(SST.DESCRIPTION AS VARCHAR(100)) AS SERVICESUBTYPEDESC
, DATEADD(DD,0, DATEDIFF(DD,0,EV.GETRPSSTARTTIMESTAMP)) AS EVENTSTARTDATE
, CONVERT(CHAR(5),EV.GETRPSSTARTTIMESTAMP,8) AS EVENTSTARTTIME
, DATEADD(DD,0, DATEDIFF(DD,0,EV.GETRPSENDTIMESTAMP)) AS EVENTENDDATE
, CONVERT(CHAR(5),EV.GETRPSENDTIMESTAMP,8) AS EVENTENDTIME
,CAST(VEN.DESCRIPTION AS VARCHAR(12)) AS EVENTVENUE
,EV.ISCOMPLETED
, EV.ISFINALISED
,EV.ISREVOKED
, DATEADD(DD,0, DATEDIFF(DD,0,EV.REVOKEDON)) AS REVOKEDDATE
, EV.OID
from Event ev
LEFT OUTER JOIN ServiceType AS st ON ev.myServiceType = st.oid
LEFT OUTER JOIN ServiceSubtype AS sst ON ev.myServiceSubtype = sst.oid
LEFT OUTER JOIN AllCodes AS ven ON ev.myEventVenueCode = ven.oid
)as EV
ON ASM.MYEVENT = EV.OID
LEFT OUTER JOIN (
select wu.oid
,CAST(wu.providerid AS VARCHAR(100)) AS providerid
,CAST(nm.getfullname AS VARCHAR(100)) AS ProviderName
,wu.contactname
,wu.activatedate as StartDate
,wu.deactivatedate as EndDate
,case when wu.deactivatedate is null then 1 else 0 end as IsActiveToday
from workunitprovider wu
LEFT OUTER JOIN dbo.allprovidernames nm ON wu.oid = nm.myprovider
where nm.myNameType in (02245.0000000252)
) as WU
ON ASM.MYWORKUNITPROVIDER = WU.OID
Left join (
select f.myEvent
,f.myProvider
,f.myproviderrolecode
,f.Max_ProvOid
,CAST(g.providerid AS VARCHAR(100)) AS providerid
,CAST( i.description AS VARCHAR(150)) AS ProviderRole
,cast (h.getFullName as nvarchar (150)) as ProviderName
from( select d.myEvent
,myProvider
,myproviderrolecode
,d.Max_ProvOid
from ( select A.myEvent, max(b.oid) as Max_ProvOid
from alleventitems a
left outer join ProviderEventItemRole as b on a.oid = b.myeventitem
group by A.myEvent
) as d
left join
( select A.myEvent,b.myProvider,b.myproviderrolecode,a.oid as a_oid,b.oid as b_oid
from alleventitems a
left outer join ProviderEventItemRole as b on a.oid = b.myeventitem
)as e on d.myevent = e.myevent and max_provOid = b_oid
) as f
left join dbo.allproviders as g on f.myProvider = g.oid
left join (
select *
from dbo.AllProviderNames
where mynametype ='02245.0000000252'
)as h on f.myprovider =h.myprovider
left join dbo.allcodes as i on f.myproviderrolecode = i.oid
)as j on ASM.myevent = j.myevent;
Before we begin, a disclaimer:
Complex SELECT queries are best expressed in T-SQL. SSIS is best used for ETL tasks.
Now... with that out of the way. Let's see what we have. That query has fifteen LEFT JOINS nested across three levels: Five at the top, seven at the middle, and two at the bottom. Peppered throughout are a some CAST()s and GROUP BYs. All of those SQL commands can be done with SSIS components.
JOIN = Merge Join component.
GROUP BY = Aggregate component.
CAST = Derived Column component.
Since you have such a large query, I'd recommend breaking this into smaller chunks. Starting with the inner most join.
select
d.myEvent
,myProvider
,myproviderrolecode
,d.Max_ProvOid
from (
select A.myEvent, max(b.oid) as Max_ProvOid
from alleventitems a
left outer join ProviderEventItemRole as b
on a.oid = b.myeventitem
group by A.myEvent
) as d
left join (
select A.myEvent,b.myProvider,b.myproviderrolecode,a.oid as a_oid,b.oid as b_oid
from alleventitems a
left outer join ProviderEventItemRole as b
on a.oid = b.myeventitem
) as e
Translating that to SSIS would look like this.
Above, we're merging four tables into one. You can learn more about how to configure Merge Joins here. Repeat the above pattern for the remaining JOINS and connect them all together and you will have translated the entire query to SSIS!
Now that we can see how it may be done, may I ask why we'd want to do this in SSIS?

Use Multiple Varchar as a parameter

I am trying to create a query that will allow me to use multiple VarChars as a parameter in SSRS.
Here's the code:
Declare #CallCodes as VarChar(10)
Set #CallCodes = ('MORC30' , 'Morc60')
;
With Data
AS
(SELECT
VC.[CallCode]
,VC.[HospCode]
,VC.[HospMastID]
,VC.[ClientID]
,Row_Number () Over (Partition By HospMastID, VC.ClientID Order By HospMastID, VC.ClientID, GLCode) as Txn
FROM
[RptSys].[dbo].[CSC_VuesionImport_DevDetl] as VC
Inner Join
[AVimark_OLTP].[dbo].[Client] as C
on
VC.HospMastID = C.HospitalMasterID
and
VC.ClientID = C.ClientID
Inner Join
[Avimark_OLTP].[dbo].[Patient] as P
on
VC.HospMastID = P.HospitalMasterID
and
VC.PatientID = P.PatientID
Inner Join
[Avimark_OLTP].[dbo].[Treatment] as T
on
VC.HospMastID = T.HospitalMasterID
and
VC.MastReminder = T.Code
Where
VC.CallCode in #CallCodes)
This gives an error when I try to run it. The final output is to allow the end user to choose from a drop down list in an SSRS report I have tried all variations of in or like for the where statement.
Any suggestions would be greatly appreciated.
Why don't you take the Parmaeter in a temporary table marked with #
CREATE TABLE #tmp(
Callcodes varchar(10))
INSERT INTO #tmp
VALUES
('MORC30'),
('Morc60')
With Data
AS
(SELECT
VC.[CallCode]
,VC.[HospCode]
,VC.[HospMastID]
,VC.[ClientID]
,Row_Number () Over (Partition By HospMastID, VC.ClientID Order By HospMastID, VC.ClientID, GLCode) as Txn
FROM
[RptSys].[dbo].[CSC_VuesionImport_DevDetl] as VC
Inner Join
[AVimark_OLTP].[dbo].[Client] as C
on
VC.HospMastID = C.HospitalMasterID
and
VC.ClientID = C.ClientID
Inner Join
[Avimark_OLTP].[dbo].[Patient] as P
on
VC.HospMastID = P.HospitalMasterID
and
VC.PatientID = P.PatientID
Inner Join
[Avimark_OLTP].[dbo].[Treatment] as T
on
VC.HospMastID = T.HospitalMasterID
and
VC.MastReminder = T.Code
Where
VC.CallCode in (SELECT * FROM #tmp))
I hope this is what you are looking for, if not please tell me. Or like mentioned in the comments give a error message
Have a nice day & greets from Switzerland
Etienne

Efficient sql server paging

Due to the first two comments I've removed all my own code and placed the example directly from 4 guys here.
I'm interested in how the 'select #first_id' should be coded. The example shows the rows being pulled using joins and I would expect that the first_id wouldn't be a valid place to start because it doesn't use the same join syntax.
CREATE PROCEDURE [dbo].[usp_PageResults_NAI]
(
#startRowIndex int,
#maximumRows int
)
AS
DECLARE #first_id int, #startRow int
-- A check can be added to make sure #startRowIndex isn't > count(1)
-- from employees before doing any actual work unless it is guaranteed
-- the caller won't do that
-- Get the first employeeID for our page of records
SET ROWCOUNT #startRowIndex
SELECT #first_id = employeeID FROM employees ORDER BY employeeid
-- Now, set the row count to MaximumRows and get
-- all records >= #first_id
SET ROWCOUNT #maximumRows
SELECT e.*, d.name as DepartmentName
FROM employees e
INNER JOIN Departments D ON
e.DepartmentID = d.DepartmentID
WHERE employeeid >= #first_id
ORDER BY e.EmployeeID
SET ROWCOUNT 0
GO
You can to efficient paging using ROW_NUMBER()
DECLARE #skipRows Int = 10 --Change to input parameter to sp
DECLARE #takeRows Int = 20 --Change to input parameter to sp
SELECT *
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY a.DateCreated) As RowNumber,
a.PKID,
a.AlertUrl,
a.AlertDescription,
a.Users_PKID_creator,
dbo.Users_GetFullName(a.Users_PKID_creator) as Users_FullName,
a.Dealers_PKID,
d.Dealer,
dbo.convertDateFromUTC(a.DateCreated, #dealers_pkid) as DateCreated,
dbo.convertDateFromUTC(a.DateCreated, #dealers_pkid) as ComparisonDate,
dbo.convertDateFromUTC(a.DateModified, #dealers_pkid) as DateModified,
a.Active,
a.Contacts_PKID,
dbo.Contacts_GetFullName(a.Contacts_PKID) as Contacts_FullName
from Alerts a
join Dealers d on d.PKID = a.Dealers_PKID
where a.DateCreated between dbo.convertDateToUTC(#datetimeDateStart, #dealers_pkid) and dbo.convertDateToUTC(#datetimeDateEnd, #dealers_pkid)
and a.Active = #bitActive
and a.PKID >= #first_id
) AS [t1]
WHERE [t1].RowNumber BETWEEN #skipRows + 1 AND #skipRows + #takeRows

Need help on a stored procedure in SQL Server 2008

I have 4 tables:
Table1
ContentID(pk)
ContentGUID
Description
SiteID
CategoryID
StartDate
DisplayName
ParentId
AssignedAuthors
AssignedEditors
CreatedBy
U.UserName
Created
ModifiedBy
UserName
Modified
Priority
Table2
ContentID(fk)
versionid(pk)
page
Table3
apprhistroyid(pk)
verstionid(fk)
approvalstatusid(fk)
Table4
approvalstatusid(pk)
statusname
I want the total details of table1 and table4. I have tried the following procedure:
ALTER PROCEDURE [dbo].[DEV_SiteAdmin_Menu_GetItem_ALL_TEMP]
#SiteID Int
AS
DECLARE #VersionID int, #ApprovalStatusID int,#StatusName nvarchar(max),#ContentID Int,#Rowcount int
DECLARE #TEMP INT
--set #ApprovalStatusID=5;
--set #StatusName ='New';
set #Rowcount=(select max(ContentID)from dev_content where SiteID=#SiteID)
set #ContentID=(select min(ContentID) from dev_content where SiteID=#SiteID)
SET #TEMP=#ContentID
IF(#Rowcount>=1)
BEGIN
WHILE #Rowcount>1
BEGIN
SET #Rowcount=#Rowcount-1
set #ApprovalStatusID=
CASE
WHEN exists (SELECT VersionID from DEV_ContentVersion WHERE ContentID=#TEMP)
THEN (SELECT ApprovalStatusID FROM DEV_ApprovalStatus WHERE ApprovalStatusID=(SELECT ApprovalStatusID FROM DEV_ApprovalHistory WHERE VersionID=(SELECT VersionID from DEV_ContentVersion WHERE ContentID=(select ContentID from dev_content where ContentID=#ContentID and SiteID=#SiteID)))) else 5 end
set #StatusName=
case
when (#ApprovalStatusID != 5)
then
(SELECT StatusName FROM DEV_ApprovalStatus WHERE ApprovalStatusID=#ApprovalStatusID)
else
'New'
end
SELECT DISTINCT [ContentID]
,[ContentGUID]
,[Description]
,[SiteID]
,[CategoryID]
,[StartDate]
,[DisplayName]
,[ParentId]
,[AssignedAuthors]
,[AssignedEditors]
,[CreatedBy]
,U.UserName 'CreatedUser'
,dbo.fnGetUserNamesFromUserIds([AssignedAuthors],',') 'Authors'
,dbo.fnGetUserNamesFromUserIds([AssignedEditors],',') 'Editors'
,[Created]
,[ModifiedBy]
,U1.UserName 'ModifiedUser'
,[Modified]
,[Priority]
,#ApprovalStatusID [ApprovalStatusID]
,#StatusName [StatusName]
FROM [DEV_Content] C
INNER JOIN dbo.aspnet_Users U ON U.UserId=C.CreatedBy
INNER JOIN dbo.aspnet_Users U1 ON U1.UserId=C.ModifiedBy
WHERE C.SiteID=#SiteID AND [ContentID] = #TEMP
SET #TEMP= #TEMP+1
END
END
else
print 'error'
Where I am getting n no.of rowa that is it returns per 1 contentid 1 row instead I want all return values as one table.
I think your whole query can be boiled down to:
SELECT
[ContentID]
,[ContentGUID]
,[Description]
,[SiteID]
,[CategoryID]
,[StartDate]
,[DisplayName]
,[ParentId]
,[AssignedAuthors]
,[AssignedEditors]
,[CreatedBy]
,U.UserName as CreatedUser
,dbo.fnGetUserNamesFromUserIds([AssignedAuthors],',') as Authors
,dbo.fnGetUserNamesFromUserIds([AssignedEditors],',') as Editors
,[Created]
,[ModifiedBy]
,U1.UserName as ModifiedUser
,[Modified]
,[Priority]
,COALESCE(ah.ApprovalStatusID,5) as ApprovalStatusID
,COALESCE(ast.StatusName,'New' as StatusName
FROM
[DEV_Content] C
INNER JOIN
dbo.aspnet_Users U
ON
U.UserId=C.CreatedBy
INNER JOIN
dbo.aspnet_Users U1
ON
U1.UserId=C.ModifiedBy
left join
DEV_ContentVersion cv
inner join
DEV_ApprovalHistory ah
on
cv.VersionID = ah.VersionID
inner join
DEV_ApprovalStatus ast
on
ah.ApprovalStatusID = ast.ApprovalStatusID
on
C.ContentID = cv.ContentID
WHERE
C.SiteID=#SiteID
But I have to admit, I'm not sure what the DISTINCT was meant to be doing in there.