Need help on a stored procedure in SQL Server 2008 - 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.

Related

Handling Multi Value Parameters in SSRS

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.

How do I select two columns containing different data from the same field

I am trying to select two different data descriptions from the same field. The data is differentiated by the Type and ID columns in the same table. Below is the query I am trying but I am getting duplicate data results. Attached are screenshots of the two tables and the query results.
SELECT SEX,[ADDRESS],CITY,SOC_SEC_NUM,ZIP,ect...
CASE WHEN CD.[TYPE] = 'COUNTY'
THEN CD.[DESC]
END AS COUNTY,
--CASE WHEN CDTBL1.[TYPE] = 'ETH'
--THEN CDTBL1.[DESC]
--END AS ETH
CDTBL1.[DESC] AS ETH
--CD.[DESC] AS COUNTY
--INTO #TMP
FROM CDCLIENT
INNER JOIN CDTBL1
ON CDCLIENT.ETH_ID = CDTBL1.ID
INNER JOIN CDTBL1 CD
ON CAST(CDCLIENT.RES_COUNTY_ID AS VARCHAR) = CD.ID
WHERE CDTBL1.[TYPE] = 'ETH'
--AND CD.[DESC] IS NOT NULL
--OR
--CD.[TYPE] = 'COUNTY'
ORDER BY LAST_NAME ASC
--SELECT * FROM #TMP
--WHERE COUNTY IS NOT NULL
I think the problem is that you have duplicate ID's. I would add some another condition to your join for the TYPE.
SELECT SEX,[ADDRESS],CITY,SOC_SEC_NUM,ZIP,ect...
CASE WHEN CD.[TYPE] = 'COUNTY'
THEN CD.[DESC]
END AS COUNTY,
--CASE WHEN CDTBL1.[TYPE] = 'ETH'
--THEN CDTBL1.[DESC]
--END AS ETH
CDTBL1.[DESC] AS ETH
--CD.[DESC] AS COUNTY
--INTO #TMP
FROM CDCLIENT
INNER JOIN CDTBL1
ON CDCLIENT.ETH_ID = CDTBL1.ID AND CDTBL1.TYPE = 'ETH'
INNER JOIN CDTBL1 CD
ON CAST(CDCLIENT.RES_COUNTY_ID AS VARCHAR) = CD.ID AND CD.TYPE = 'COUNTY'
WHERE CDTBL1.[TYPE] = 'ETH'
--AND CD.[DESC] IS NOT NULL
--OR
--CD.[TYPE] = 'COUNTY'
ORDER BY LAST_NAME ASC
--SELECT * FROM #TMP
--WHERE COUNTY IS NOT NULL
In addition to SQLChao response, you also can replace your initial SELECT by SELECT DISTINCT, with this option you remove duplicated results.

Update Query With Inline

Is it possible to do an update query like this? It may not be, just a thought I had as to possibly a solution to my predicament of terrible data-structure. What I am trying to accomplish is:
To update the table prodinformation with a count where the entrytype exists in table vet
Set #location varchar(100), #entrydate datetime
Set #location = 'server01.database01.dbo.manhunt
Set #entrydate = GetDate()
Update prodinformation
Set totalenteredtoday = abc.te
FROM prodinformation d
JOIN (SELECT Count(ID)
from #location
WHERE entrytype IN (
Select validentrytype
from vet
where ltrim(rtrim(entrydate)) = #entrydate) As te
Update d
Set totalenteredtoday = te.IdCount
FROM prodinformation As d
JOIN
(
Select [someJoinAttribute]
,Count(ID) As IdCount
From #location
Where entrytype IN ( Select validentrytype
From vet With (Nolock)
Where ltrim(rtrim(entrydate)) = #entrydate
)
Group By [someJoinAttribute]
) As te On d.[someAttribute] = te.[someJoinAttribute]
here [someJoinAttribute] would be the column/attribute to be used to perform join operation

Getting Round The SubQuery Returned More Than 1 Value Error

I am trying to get a reading of time spent in class, and my query keeps producing the error of
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
How can I get around this?
Declare
#timespentinclass decimal(18,2),
#courseID varchar(50),
#course varchar(50),
#studentID varchar(50),
#count int
Set #courseID = '2'
Create Table Course (course varchar(MAX),coursename varchar(MAX),timespentinclass int,studentID varchar(50),dun int)
Create Table coursesOffered(course varchar(Max),courseIDUsed varchar(50),courseID varchar(50))
Create Table timespentinclass(coursetaken varchar(Max),studentID varchar(50),studentinfo varchar(MAX),daysattended decimal(18,2))
SET #count = (SELECT COUNT(*) FROM courses)
while #count > 0
BEGIN
SET #course = (SELECT TOP 1 course FROM courses WHERE dun IS NULL)
SET #courseID = (SELECT TOP 1 courseIDUsed FROM coursesOffered WHERE courseID = #course)
BEGIN
set #timespentinclass = (select (convert(decimal(18,2),SUM(daysattended)),2)
from timespentinclass t
RIGHT JOIN courses al
ON t.studentID = al.studentID
where course = #courseID
and t.studentID = al.studentID)
END
update course set
timespentinclass = #timespentinclass
where course = #course
and dun is null
set #count = #count - 1
UPDATE courses
SET dun = 1
WHERE studentID = #studentID
END
EDIT 1
Adding in Top 1 to this statement will no longer produce the error, but it gives the same value for timespentinclass for all students for that class?
set #timespentinclass = (select Top 1(convert(decimal(18,2),SUM (daysattended)),2)
from timespentinclass t
RIGHT JOIN courses al
ON t.studentID = al.studentID
where course = #courseID
and t.studentID = al.studentID)
I think I found the problem. Look at this:
(select (convert(decimal(18,2),SUM(daysattended)), 2)
Here you are selecting converted value and 2. You are misplaced brackets. I think it should be:
set #timespentinclass = (select convert(decimal(18,2), SUM(daysattended), 2)
from timespentinclass t
RIGHT JOIN courses al
ON t.studentID = al.studentID
where course = #courseID
and t.studentID = al.studentID)
But I always prefer the following syntax:
select #timespentinclass = convert(decimal(18,2), SUM(daysattended), 2)
from timespentinclass t
RIGHT JOIN courses al ON t.studentID = al.studentID
where course = #courseID
I believe below code block is creating the issue
set #timespentinclass = (select (convert(decimal(18,2),SUM(daysattended)),2)
from timespentinclass t
RIGHT JOIN courses al
You can either use TOP keyword to get a single data record (OR) declare #timespentinclass as a table variable to get around the issue.

How to count something in a mysql procedure?

I have written a procedure that shows me the image path from picture table and I want to calculate the no. of unread messages.Here is what i am doing
CREATE PROCEDURE datehate.dashboard_message(IN UserID INT)
BEGIN
SELECT picture.path_thumb,status
FROM picture,message,user_profile
WHERE (
(message.receiver_user_id=UserID)
AND
(user_profile.user_id=message.sender_user_id AND picture.picture_id=user_profile.picture_id)
);
END
And this the output i am getting
path_thumb status
E:\DateOrHateUser\DEMO_2_Stockhlom\images\Male\1#j... UNREAD
E:\DateOrHateUser\DEMO_2_Stockhlom\images\Male\3#j... READ
E:\DateOrHateUser\DEMO_2_Stockhlom\images\Male\5#j... UNREAD
use
SELECT count(*)
to get the number of records returned
and put
status="UNREAD"
in your WHERE condition
How about -
CREATE PROCEDURE datehate.dashboard_message(IN UserID INT)
BEGIN
SELECT p.path_thumb, SUM(IF(m.status = 'UNREAD', 1, 0)) AS unread_msgs
FROM message m
INNER JOIN user_profile up
ON m.sender_user_id = up.user_id
INNER JOIN picture p
ON up.picture_id = p.picture_id
WHERE m.receiver_user_id=UserID
GROUP BY m.sender_user_id, p.path_thumb;
END
EDIT I have modified the above query to give the count of unread messages without excluding senders for whom you have no unread messages. Sorry, I misunderstood your question.
or this which will give you the count of messages in each status -
CREATE PROCEDURE datehate.dashboard_message(IN UserID INT)
BEGIN
SELECT p.path_thumb, m.status, COUNT(*) AS msgs
FROM message m
INNER JOIN user_profile up
ON m.sender_user_id = up.user_id
INNER JOIN picture p
ON up.picture_id = p.picture_id
WHERE m.receiver_user_id=UserID
GROUP BY m.sender_user_id, p.path_thumb, m.status;
END