how to using distinct in XML SQL using stored procedure - sql-server

SELECT DISTINCT
CD.CASE_NO AS CaseNumber ,
CE.PROCEEDING_ID AS ProceedingId,
PR.AC_STATE_CD AS ForeclosureStatecode,
0 AS STATUS,
GETDATE() AS CreatedDate,
1 AS CreatedBy,
GETDATE() AS ModifiedDate,
1 AS ModifiedBy,
(
select * from TBL_PROPERTY FOR XML PATH('T')
)
from TBL_CASE_DETAIL CD WITH(NOLOCK)
INNER JOIN TBL_AUCTION_DETAIL AD WITH(NOLOCK) ON AD.CASE_DETAIL_ID = CD.CASE_DETAIL_ID
LEFT JOIN TBL_AUCTION_PROPERTY_MAPPING TAPM WITH(NOLOCK) ON TAPM.AUCTION_ID = AD.AUCTION_ID
LEFT JOIN TBL_PROPERTY PR WITH(NOLOCK) ON PR.PROPERTY_ID = TAPM.PROPERTY_ID
LEFT JOIN TBL_AUCTION_PROCEEDING_MAPPING APM WITH(NOLOCK) ON APM.AUCTION_ID = AD.AUCTION_ID
FOR XML PATH('Foreclosure')
Hi Guys, This is my modified code to get a distinct result. but now property part cannot display properly..
This is the result I get it. suppose open another tab for property lets say have 3 property.. so in 1 tab of foreclosure,inside foreclosure have 3 property data, then close foreclose tab..
https://gyazo.com/8a54690c88df3e9bb0dd7ff916c6f86c
Thank You.

If I get this right, the only thing you have to add is ,TYPE. Otherwise your inner SELECT ... FOR XML PATH() is filled i as text with all forbidden characters escaped...
Try:
(
select * from TBL_PROPERTY FOR XML PATH('T'),TYPE
)

Related

using distinct in select having joins with multiple table

Trying to use Distinct in select statement but not getting the desired result. I want CaseID to be returned for the last updated comment only. Below is the query that I am trying to use.
Select Distinct av.CaseID,fr.Rule_Description, av.Date, av.Status, fr.RULE_PRIORITY, ac.User_comments, max(ac.Comment_PostDate),ac.UserID
From tblAlertView av
Join tblAlertComment ac
on av.CaseID = ac.CaseID
Join tblFBLRule fr
on av.RuleID = fr.Rule_ID
Join TBLUSER usr
on ac.UserID = usr.USERID
group by av.CaseID, fr.Rule_Description, av.Date, av.Status, fr.RULE_PRIORITY, ac.User_comments, ac.Comment_PostDate,ac.UserID
Query Result
Remove
ac.Comment_PostDate
from group by clause
Rather than using JOIN to get to tblAlertComment, if you use CROSS APPLY you can specify to just return the top 1 comment per case:
SELECT av.CaseID,
fr.Rule_Description,
av.Date,
av.Status,
fr.RULE_PRIORITY,
ac.User_comments,
ac.Comment_PostDate,
ac.UserID
FROM tblAlertView AS av
INNER JOIN tblFBLRule AS fr
ON av.RuleID = fr.Rule_ID
CROSS APPLY
( SELECT TOP 1 ac.User_comments, ac.Comment_PostDate, ac.UserID
FROM tblAlertComment AS ac
INNER JOIN tblUser AS usr
ON usr.UserID = ac.UserID
WHERE ac.CaseID = av.CaseID
ORDER BY ac.Comment_PostDate DESC
) AS ac;

Create View - Declare a variable

I am creating a view that is using that STUFF function. I want to put the result of STUFF in a variable for my view. The problem I am having is declaring my variable. It gives me the message "Incorrect Syntax near 'DECLARE'. Expecting '(' or SELECT." I already have the '(' in there. I have tried putting a BEGIN before it. I have tried putting it after the SELECT word. But nothing seems to work and I cannot find a solution in my search. I am using SQL Server 2012
CREATE VIEW [AQB_OB].[GISREQUESTEDBURNS]
AS
(DECLARE #CONDITIONS AS varchar(20)
SET #CONDITIONS = (SELECT DISTINCT BD.[RequestedBurnsID]
,[ConditionsReasonsID] = STUFF((SELECT ', ' + CONVERT(VARCHAR (20),[ConditionsReasonsID]) FROM [AQB_OB].[BurnDecisions] WHERE [RequestedBurnsID]= BD.[RequestedBurnsID] ORDER BY [RequestedBurnsID] ASC
FOR XML PATH ('')) , 1 , 1, '') FROM
[AQB_OB].[BurnDecisions] BD)
SELECT RB.[RequestedBurnsID] AS REQUESTEDBURNID
,BUY.[BurnYear] AS BURNYEAR
,CY.[CurrentYear] AS CURRENTYEAR
,RB.[BurnSitesID] AS BURNSITESID
,[BurnerID] AS BURNERID
,[Contact] AS CONTACT
,[BurnDecision] AS BURNDECISION
,RB.[Comment] AS COMMENT
,#CONDITIONS AS CONDITIONS
FROM [AQB_MON].[AQB_OB].[RequestedBurns] RB
LEFT join AQB_MON.[AQB_OB].[PileDryness] PD on RB.[PileDrynessID] = PD.[PileDrynessID]
inner join AQB_MON.[AQB_OB].[BurnYear] BUY on BUY.BurnYearID = BP.BurnYearID
inner join AQB_MON.[AQB_OB].[CurrentYear] CY on CY.CurrentYearID = BUY.CurrentYearID
GO
You can't declare variables in a view. Could you make it into a function or stored procedure?
Edit - you might also be able to put something into a CTE (Common Table Expression) and keep it as a view.
e.g.
WITH conditions as
(
... do the STUFF here
)
SELECT blah
FROM blah
INNER JOIN conditions
(or CROSS JOIN conditions if its just one row, I can't quite decipher what your data is like)
Here is a sample query that uses a CTE (Common Table Expression) to nicely emulate internal variable construction, as described by James Casey. You can test-run it in your version of SQL Server.
CREATE VIEW vwImportant_Users AS
WITH params AS (
SELECT
varType='%Admin%',
varMinStatus=1)
SELECT status, name
FROM sys.sysusers, params
WHERE status > varMinStatus OR name LIKE varType
SELECT * FROM vwImportant_Users
yielding output:
status name
12 dbo
0 db_accessadmin
0 db_securityadmin
0 db_ddladmin
also via JOIN
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers INNER JOIN params ON 1=1
WHERE status > varMinStatus OR name LIKE varType
also via CROSS APPLY
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers CROSS APPLY params
WHERE status > varMinStatus OR name LIKE varType
Or use a CTE (common table expression) as subselect like:
WITH CTE_Time(Clock)
AS(
SELECT 11 AS [Clock] -- set var
)
SELECT
DATEPART(HOUR, GETDATE()) AS 'actual hour',
CASE
WHEN DATEPART(HOUR, GETDATE()) >= (SELECT [Clock] FROM CTE_Time) THEN 'after'
ELSE 'before'
END AS [Data]
Try put the condition subquery directly inside the the view select statement. you may CAST the XML to VARCHAR(20).
CREATE VIEW [AQB_OB].[GISREQUESTEDBURNS]
AS
SELECT RB.[RequestedBurnsID] AS REQUESTEDBURNID
,BUY.[BurnYear] AS BURNYEAR
,CY.[CurrentYear] AS CURRENTYEAR
,RB.[BurnSitesID] AS BURNSITESID
,[BurnerID] AS BURNERID
,[Contact] AS CONTACT
,[BurnDecision] AS BURNDECISION
,RB.[Comment] AS COMMENT,
(
SELECT DISTINCT BD.[RequestedBurnsID],
[ConditionsReasonsID] = STUFF((SELECT ', ' + CONVERT(VARCHAR (20), [ConditionsReasonsID]) FROM [AQB_OB].[BurnDecisions]
WHERE [RequestedBurnsID]= BD.[RequestedBurnsID] ORDER BY [RequestedBurnsID] ASC
FOR XML PATH ('')) , 1 , 1, '') FROM
[AQB_OB].[BurnDecisions] BD
) AS CONDITIONS
FROM [AQB_MON].[AQB_OB].[RequestedBurns] RB
LEFT join AQB_MON.[AQB_OB].[PileDryness] PD on RB.[PileDrynessID] = PD.[PileDrynessID]
inner join AQB_MON.[AQB_OB].[BurnYear] BUY on BUY.BurnYearID = BP.BurnYearID
inner join AQB_MON.[AQB_OB].[CurrentYear] CY on CY.CurrentYearID = BUY.CurrentYearID

how to use this without subquery. I need to use with join to get same result set

How to use this below query as join instead of subquery. It's resulting poor performance
SELECT EBIJ.* FROM BUDLINEITEMS EBIJ
WHERE ReferenceId NOT IN (SELECT ImportKeyId FROM External_Blk_Itm_JounalEntries)
SELECT EBIJ.*
FROM BUDLINEITEMS EBIJ
LEFT JOIN External_Blk_Itm_JounalEntries E
ON EBIJ.ReferenceId = E.ImportKeyId
WHERE E.ImportKeyId IS NULL
OR
SELECT EBIJ.* FROM BUDLINEITEMS EBIJ
WHERE NOT EXISTS (SELECT 1
FROM External_Blk_Itm_JounalEntries E
WHERE EBIJ.ReferenceId = E.ImportKeyId )

Multiple values from subquery

I want to generalise my query at the bottom so I get all the projects and additional project info where my subgroup has a certain value but I can't get this to work because I can't get the [ProjectFk]
SELECT
[HeadCount].[ID],
[LinkProjectAreaFk],
[Month1],
[Month2],
[Month3],
[Month4],
[Month5],
[Month6],
[Month7],
[Month8],
[Month9],
[Month10],
[Month11],
[Month12],
[HcYear],
[ApproveDirFk],
[ApproveDirDate],
[FreezeFk],
[freezeDate],
[CDSID],[FreezeTypeFk],
[ApproveDirTypeFk],
[SourcesFk],
[Project].[Title],
[Project].[Title]
FROM
[HeadCount],
[Project]
WHERE
[HeadCount].[LinkProjectAreaFk]
IN
(SELECT
[ID]
FROM
[LinkProject-Area]
WHERE
[SubgroupFk]=1)
and
[Project].[ID]=[LinkProject-Area].[ProjectFk]
The following query works but is only for one project how can I also get the projectFk from my subquery, because when I look this up they say it's not possible and with a left outer join I can't get it to work at all
SELECT
[HeadCount].[ID],
[LinkProjectAreaFk],
[Month1],
[Month2],
[Month3],
[Month4],
[Month5],
[Month6],
[Month7],
[Month8],
[Month9],
[Month10],
[Month11],
[Month12],
[HcYear],
[ApproveDirFk],
[ApproveDirDate],
[FreezeFk],
[freezeDate],
[CDSID],
[FreezeTypeFk],
[ApproveDirTypeFk],
[SourcesFk],
[Project].[Title],
[Project].[Title]
FROM
[HeadCount],
[Project]
WHERE
[HeadCount].[LinkProjectAreaFk] IN
(SELECT
[ID]
FROM
[LinkProject-Area]
WHERE
[ProjectFk]=90
and
[SubgroupFk]=1)
and
[Project].[ID]=90
Hope you can help me out or point me in the right direction
Kind regards
Hi I've been trying your way but it's still not going as it should:
I'me getting the multi-part identifier "MyCTE.ProjectFK" could not be bound. and
The multi-part identifier "MyCTE.ID" could not be bound. error when I look this up is has something to do with using my joins wrong any ideas?
;WITH MyCTE (ID, ProjectFK)
AS
(
SELECT
ID,
ProjectFk
FROM
[LinkProject-Area]
WHERE
SubgroupFk = 1
)
SELECT
*
FROM
[LinkProject-Area]
INNER JOIN
HeadCount ON [LinkProjectAreaFk] = MyCTE.ID
INNER JOIN
Project ON Project.ID = MyCTE.ProjectFK
I think you're going to want to organize this query as something like this:
SELECT ...
FROM
(
SELECT ID, ProjectFk
FROM [LinkProject-Area]
WHERE SubgroupFk = 1
) LinkProjectAreas
INNER JOIN HeadCount ON LinkProjectAreaFK = LinkProjectAreas.ID
INNER JOIN Project ON Project.ID = LinkProjectAreas.ProjectFK
You could also organize this with a Common Table Expression (CTE):
;WITH LinkProjectAreas (ID, ProjectFK) AS
(
SELECT ID, ProjectFk
FROM [LinkProject-Area]
WHERE SubgroupFk = 1
)
SELECT ...
FROM LinkProjectAreas
INNER JOIN HeadCount ON LinkProjectAreaFK = LinkProjectAreas.ID
INNER JOIN Project ON Project.ID = LinkProjectAreas.ProjectFK

SQL Subquery Select Table based on Outer Query

I have a general query that looks like this:
SELECT DISTINCT pb.id, pb.last, pb.first, pb.middle, pb.sex, pb.phone, pb.type,
specialties = substring(
SELECT ('|' + cs.specialty )
FROM CertSpecialty AS cs
INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
WHERE cs.id = pb.id
ORDER BY cs.sequence_no
FOR XML path(''),2,500)
FROM table AS pb
WHERE etc etc etc
The issue is this:
The "type" column that I'm selecting is an integer - types 1-4.
In the subquery, see where I am querying from the table CertSpecialty right now.
What I actually need to do is, if the type field comes back as a 1 or a 3, that's the table I need to query. But if the row's result is a type 2 or 4 (i.e., an ELSE), I need to be querying the same column in the table CertSpecialtyOther.
So it'd need to look something like this (though this obv doesn't work):
SELECT DISTINCT pb.id, pb.last, pb.first, pb.middle, pb.sex, pb.phone, pb.type,
specialties =
IF type in (1,3)
substring((SELECT ('|' + cs.specialty )
FROM CertSpecialty AS cs
INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
WHERE cs.id = pb.id
ORDER BY cs.sequence_no
FOR XML path(''),2,500)
ELSE
substring((SELECT ('|' + cs.specialty )
FROM CertSpecialtyOther AS cs
INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
WHERE cs.id = pb.id
ORDER BY cs.sequence_no
FOR XML path(''),2,500)
end
FROM table AS pb
WHERE etc etc etc
Is this possible? If so, what is the correct syntax? Is there a simpler way to write it where I'm switching which table I query without completely duplicating the subquery?
Also, does anyone have a good resource they could link me for this sort of thing to learn more besides?
Thanks in advance.
Use a CTE.
;WITH cs AS
(
SELECT 'A' SpecialtyCategory, phy_key, specialty
FROM CertSpecialty
UNION ALL
SELECT 'B' SpecialtyCategory, phy_key, specialty
FROM CertSpecialtyOther
)
SELECT csi.id, cs.specialty
FROM cs
INNER JOIN CertSpecialtyIndex AS csi on cs.specialty = csi.specialty
WHERE cs.phy_key = pb.phy_key
AND cs.SpecialtyCategory = (CASE WHEN type in (1,3) THEN 'A' ELSE 'B' END)

Resources