Related
Item table
id key code description
------------------------------
1 1 misc miscellaneous
2 1 med medicine
Miscellaneous table:
id code description
------------------------
1 misc1 miscellaneous
2 misc1 miscellaneous
Medicine table:
id code description
---------------------------
1 medicine1 medicine
2 medicine1 medicine
I have this table structure; my main table is the Item table and I want to JOIN the main table with other table based on the column value in main table. The column that determines the table to be joined is code. If code is misc join with misc table if value is med join with medicine table.
I know the basic JOIN of table like
SELECT *
FROM item
INNER JOIN miscellaneous ON item.key = miscellaneous.id
But I don't know how to join when there is a condition that will point to which table to JOIN
You can use left join. Something like this:
select i.*,
coalesce(mi.code, me.code) as code_1,
coalesce(mi.description, me.description) as description_1
from item i left join
miscellaneous mi
on mi.code = i.key and i.code = 'misc' left join
medicine me
on me.code = i.key and i.code = 'med';
You can try a LEFT JOIN, that will be the easiest method to implement this.
But if you want both the table result to come under one column name, use UNION ALL
Using UNION ALL
SELECT *
FROM item i
INNER JOIN miscellaneous m on m.code=i.code
UNION ALL
SELECT *
FROM item i
INNER JOIN medicine me on me.code=i.code
Using LEFT JOIN
SELECT *
FROM item i
LEFT JOIN miscellaneous m on m.code=i.code
LEFT JOIN medicine me on me.code=i.code
Since Item is your 'base' / main table, you could match other tables with LEFT JOIN so that all rows from Item tables are present.
SELECT *
FROM Item AS i
LEFT JOIN Miscellaneous AS mi ON (mi.[id] = i.[key] AND i.code = 'misc')
LEFT JOIN Medicine AS me ON (me.[id] = i.[key] AND i.code = 'med');
You could also combine Miscellaneous & Medicine tables columns using ISNULL() function with some pre-condition
SELECT i.*
, ISNULL(mi.id, me.id) AS m_id
, ISNULL(mi.code, me.code) AS m_code
, ISNULL(mi.description, me.description) AS m_description
FROM Item AS i
LEFT JOIN Miscellaneous AS mi ON (mi.id = i.[key] AND i.code = 'misc')
LEFT JOIN Medicine AS me ON (me.id = i.[key] AND i.code = 'med');
SqlFiddle Demo
You can do this in a dynamic way
preparation of the data set for testing
IF (OBJECT_ID('item') IS NULL)
BEGIN
CREATE TABLE item (id int, [key] nvarchar(128), code nvarchar(128),
description nvarchar(512))
INSERT INTO item (id, [key] , code, description)
SELECT 1, 1, 'misc', 'miscellaneous' UNION ALL
SELECT 2, 1, 'med', 'medicine'UNION ALL
SELECT 3, 2, 'test not existing table', 'not_existing_table';
END
IF (OBJECT_ID('miscellaneous') IS NULL)
BEGIN
CREATE TABLEe miscellaneous (id int, code nvarchar(128), description
nvarchar(512))
INSERT INTO miscellaneous (id, code, description)
SELECT 1, 'misc1', 'miscellaneous' UNION ALL
SELECT 2, 'misc2', 'miscellaneous_xxx';
END
IF (OBJECT_ID('medicine') IS NULL)
BEGIN
CREATE TABLE medicine (id int, code nvarchar(128), description
nvarchar(512))
INSERT INTO medicine (id, code, description)
SELECT 1, 'medicine1', 'medicine' UNION ALL
SELECT 2, 'medicine2', 'medicine_xxx';
END
SQL Script
DECLARE #joins nvarchar(max) ='',#sql NVARCHAR(MAX) = ' SELECT * FROM item';
SELECT #joins = STUFF((SELECT ( CHAR(13)+CHAR(10) + ' LEFT JOIN ' +
description + ' ' + description + ' ON ' + description +'.id = item.[key] AND item.description = ''' + description + '''' )
FROM item i WHERE ISNULL(description,'') != '' AND
(select OBJECT_ID(description) ) IS NOT NULL
GROUP BY description
ORDER BY description
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'');
IF(ISNULL(#joins,'') != '' )
BEGIN
SET #sql = #sql + #joins;
EXECUTE sp_executesql #sql;
PRINT #sql
END;
I am new to ssrs.
I want to get all the possible data for ssrs subscribed report, which are Available in ResportServer database.
I have found some queries, but that does not have proper data. It only works for single report.
I need list of unique subscription with it's data. If possible stored procedure is preferable.
My query:
SELECT
b.name AS JobName
, e.name
, e.path
, d.description
, a.SubscriptionID
, laststatus
, eventtype
, LastRunTime
, date_created
, date_modified
FROM ReportServer.dbo.ReportSchedule a
JOIN msdb.dbo.sysjobs b
ON a.ScheduleID = b.name
JOIN ReportServer.dbo.ReportSchedule c
ON b.name = c.ScheduleID
JOIN ReportServer.dbo.Subscriptions d
ON c.SubscriptionID = d.SubscriptionID
JOIN ReportServer.dbo.Catalog e
ON d.report_oid = e.itemid
WHERE e.name = 'Sales_Report'
Thanks in advance.
I have same requirement once as like you have now...
See below stored procedure..
CREATE PROCEDURE [dbo].[GetSubscriptionData]
AS
BEGIN
SET NOCOUNT ON;
WITH
[Sub_Parameters] AS
(
SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters])
FROM [Subscriptions] a
),
[MySubscriptions] AS
(
SELECT DISTINCT [SubscriptionID], [ParameterName] = QUOTENAME(p.value('(Name)[1]', 'nvarchar(max)')), [ParameterValue] = p.value('(Value)[1]', 'nvarchar(max)')
FROM [Sub_Parameters] a
CROSS APPLY [Parameters].nodes('/ParameterValues/ParameterValue') t(p)
),
[SubscriptionsAnalysis] AS
(
SELECT a.[SubscriptionID], a.[ParameterName], [ParameterValue] =
(
SELECT STUFF((SELECT [ParameterValue] + ', ' as [text()]
FROM [MySubscriptions]
WHERE [SubscriptionID] = a.[SubscriptionID] AND [ParameterName] = a.[ParameterName]
FOR XML PATH('') ),1, 0, '') +''
)
FROM [MySubscriptions] a
GROUP BY a.[SubscriptionID],a.[ParameterName]
)
SELECT
DISTINCT (a.[SubscriptionID]),
c.[UserName] AS Owner,
b.Name,
b.Path,
a.[Locale],
a.[InactiveFlags],
d.[UserName] AS Modified_by,
a.[ModifiedDate],
a.[Description],
a.[LastStatus],
a.[EventType],
a.[LastRunTime],
a.[DeliveryExtension],
a.[Version],
sch.StartDate,
--e.[ParameterName],
--LEFT(e.[ParameterValue],LEN(e.[ParameterValue])-1) as [ParameterValue],
SUBSTRING(b.PATH,2,LEN(b.PATH)-(CHARINDEX('/',REVERSE(b.PATH))+1)) AS ProjectName
FROM
[Subscriptions] a
INNER JOIN [Catalog] AS b ON a.[Report_OID] = b.[ItemID]
Inner Join ReportSchedule as RS on rs.SubscriptionID = a.SubscriptionID
INNER JOIN Schedule AS Sch ON Sch.ScheduleID = rs.ScheduleID
LEFT OUTER JOIN [Users] AS c ON a.[OwnerID] = c.[UserID]
LEFT OUTER JOIN [Users] AS d ON a.MODIFIEDBYID = d.Userid
LEFT OUTER JOIN [SubscriptionsAnalysis] AS e ON a.SubscriptionID = e.SubscriptionID;
END
This is simplified query to get all SSRS Subscriptions
SELECT USR.UserName AS SubscriptionOwner
,SUB.ModifiedDate
,SUB.[Description]
,SUB.EventType
,SUB.DeliveryExtension
,SUB.LastStatus
,SUB.LastRunTime
,SCH.NextRunTime
,SCH.Name AS ScheduleName
,CAT.[Path] AS ReportPath
,CAT.[Description] AS ReportDescription
FROM dbo.Subscriptions AS SUB
INNER JOIN dbo.Users AS USR
ON SUB.OwnerID = USR.UserID
INNER JOIN dbo.[Catalog] AS CAT
ON SUB.Report_OID = CAT.ItemID
INNER JOIN dbo.ReportSchedule AS RS
ON SUB.Report_OID = RS.ReportID
AND SUB.SubscriptionID = RS.SubscriptionID
INNER JOIN dbo.Schedule AS SCH
ON RS.ScheduleID = SCH.ScheduleID
ORDER BY USR.UserName, CAT.[Path];
if you still have any query, comment it..
In case you need to find the sql server agent Job use this updated code
SET NOCOUNT ON;
WITH
[Sub_Parameters] AS
(
SELECT [SubscriptionID], [Parameters] = CONVERT(XML,a.[Parameters])
FROM [Subscriptions] a
),
[MySubscriptions] AS
(
SELECT DISTINCT [SubscriptionID], [ParameterName] = QUOTENAME(p.value('(Name)[1]', 'nvarchar(max)')), [ParameterValue] = p.value('(Value)[1]', 'nvarchar(max)')
FROM [Sub_Parameters] a
CROSS APPLY [Parameters].nodes('/ParameterValues/ParameterValue') t(p)
),
[SubscriptionsAnalysis] AS
(
SELECT a.[SubscriptionID], a.[ParameterName], [ParameterValue] =
(
SELECT STUFF((SELECT [ParameterValue] + ', ' as [text()]
FROM [MySubscriptions]
WHERE [SubscriptionID] = a.[SubscriptionID] AND [ParameterName] = a.[ParameterName]
FOR XML PATH('') ),1, 0, '') +''
)
FROM [MySubscriptions] a
GROUP BY a.[SubscriptionID],a.[ParameterName]
)
SELECT
DISTINCT (a.[SubscriptionID]),
j.name AS SQLServerAgentJob,
c.[UserName] AS Owner,
b.Name,
b.Path,
a.[Locale],
a.[InactiveFlags],
d.[UserName] AS Modified_by,
a.[ModifiedDate],
a.[Description],
a.[LastStatus],
a.[EventType],
a.[LastRunTime],
a.[DeliveryExtension],
a.[Version],
sch.StartDate,
--e.[ParameterName],
--LEFT(e.[ParameterValue],LEN(e.[ParameterValue])-1) as [ParameterValue],
SUBSTRING(b.PATH,2,LEN(b.PATH)-(CHARINDEX('/',REVERSE(b.PATH))+1)) AS ProjectName
FROM [Subscriptions] a
INNER JOIN [Catalog] AS b ON a.[Report_OID] = b.[ItemID]
Inner Join ReportSchedule as RS on rs.SubscriptionID = a.SubscriptionID
INNER JOIN Schedule AS Sch ON Sch.ScheduleID = rs.ScheduleID
LEFT OUTER JOIN [Users] AS c ON a.[OwnerID] = c.[UserID]
LEFT OUTER JOIN [Users] AS d ON a.MODIFIEDBYID = d.Userid
LEFT OUTER JOIN [SubscriptionsAnalysis] AS e ON a.SubscriptionID = e.SubscriptionID
LEFT JOIN msdb.dbo.sysobjects so ON rs.ScheduleID= so.name
INNER JOIN msdb.dbo.sysjobs J ON CONVERT( NVARCHAR(128), RS.ScheduleID ) = J.name
INNER JOIN msdb.dbo.sysjobschedules JS ON J.job_id = JS.job_id
I am using following query to get subscriptions and then to find SQL Jobs scripts
USE ReportServer
GO
CREATE TABLE #tempReports(LogEntryId BIGINT, subscriptionid VARCHAR(1000),LastRunTime DATETIME, _Description VARCHAR(1000), ReportID VARCHAR(1000),
LastStatus VARCHAR(1000), rowNum INT)
INSERT INTO #tempReports
SELECT *
FROM
(
SELECT DISTINCT E.LogEntryId, S.subscriptionid, LastRunTime, S.Description, E.ReportID, S.LastStatus,
ROW_NUMBER() OVER(PARTITION BY E.ReportID, S.Description ORDER BY S.LastRunTime DESC) as rowNum
FROM [ExecutionLogStorage] E
INNER JOIN Subscriptions S
ON S.Report_OID = E.ReportID
WHERE 1 = 1
AND (
S.LastStatus LIKE '%has been saved to the "\\<server>\c$\SSRS_Report_Export\20%'
)
)T
WHERE rowNum = 1
ORDER BY ReportID, Description
CREATE TABLE #ExecutionStatements (ExecStatement VARCHAR(1000), job_name VARCHAR(1000), theReportOrder INT,
LogEntryId BIGINT, subscriptionid VARCHAR(1000), LastRunTime DATETIME, _Description VARCHAR(1000),
ReportID VARCHAR(1000), LastStatus VARCHAR(1000))
INSERT INTO #ExecutionStatements
SELECT 'exec sp_start_job #job_name = ''' + cast(j.name as varchar(40)) + '''' AS ExecStatement,
j.name AS job_name,
ROW_NUMBER () OVER(ORDER BY LogEntryId) AS theReportOrder,
LogEntryId, subscriptionid,LastRunTime, _Description, ReportID,
LastStatus
from msdb.dbo.sysjobs j
join msdb.dbo.sysjobsteps js
on js.job_id = j.job_id
join #tempReports s
on js.command like '%' + cast(s.subscriptionid as varchar(40)) + '%'
WHERE 1 = 1
---Execute required statements in MSDB
SELECT E.ExecStatement + '--'+ CONVERT(VARCHAR(10),E.theReportOrder), E.theReportOrder, *
FROM #ExecutionStatements E
--WHERE subscriptionid = '3AFDAC30-4F30-423F-9F72-7C04C86026AB'
ORDER BY E.theReportOrder
SELECT DISTINCT S.subscriptionid, S.Description, E.ReportID, S.LastStatus, MAX(LastRunTime) -- 2021-04-25 18:35:00.840
FROM [ExecutionLogStorage] E
INNER JOIN Subscriptions S
ON S.Report_OID = E.ReportID
WHERE S.subscriptionid = '3AFDAC30-4F30-423F-9F72-7C04C86026AB'
GROUP BY S.subscriptionid, S.Description, E.ReportID, S.LastStatus
I'm using the AdventureWorks2008R2 sample database.
i need an output like each row should be concatenated into string(column values will be separated by commas)
This is my code:
create proc sales5
as begin
declare #SalesPersonID int
create table #table
(
id int identity(1,1) primary key clustered,
SalesPersonID int
)
create table #table1
(
SalesPersonID int null ,
PostalCode nvarchar (15) null,City varchar (30) null
)
insert into #table
select distinct
SA.BusinessEntityID
from
Sales.SalesPerson SA
join
Sales.SalesOrderHeader S on S.SalesPersonID = SA.BusinessEntityID
and S.SalesPersonID is not null
;WITH CTE
AS (
SELECT DISTINCT s.SalesPersonID
, CAST(A.PostalCode AS NVARCHAR(25)) AS PostalCode
, A.City
, CAST(s.SalesPersonID AS VARCHAR(MAX)) AS SortOrder
FROM Sales.SalesOrderHeader S(NOLOCK)
, Person.Person P(NOLOCK)
, Person.Address A(NOLOCK)
, #table t
WHERE s.SalesPersonID IS NOT NULL
AND S.SalesPersonID = P.BusinessEntityID
AND S.SalesPersonID = A.AddressID
AND S.SalesPersonID IN ('274')
UNION ALL
SELECT a.SalesOrderID
, a.SalesOrderNumber
, NULL
, C.SortOrder + CAST(a.SalesOrderID AS VARCHAR(MAX))
FROM CTE C
INNER JOIN Sales.SalesOrderHeader A(NOLOCK)
ON A.SalesPersonID = C.SalesPersonID
)
SELECT *
FROM cte
union all
select
cast ( P.BusinessEntityID as nvarchar(50)),
cast (P.NationalIDNumber as nvarchar(30)),
cast (P.Gender as nvarchar(20)),
cast (P.BusinessEntityID as VARCHAR(MAX)) + cast ('1' as VARCHAR(MAX))
from HumanResources.Employee P(nolock)
where exists(
select 1 from CTE C
where P.BusinessEntityID=C.SalesPersonID )
ORDER BY SortOrder
set nocount off
end
My output is like :
SalesPersonID PostalCode City SortOrder
274 98027 Issaquah 274
274 502097814 M 2741
43849 SO43849 NULL 27443849
44082 SO44082 NULL 27444082
44508 SO44508 NULL 27444508
44532 SO44532 NULL 27444532
My Expected Output:
274,98027,Issaquah
274,502097814,M
43849,SO43849
44082,SO44082
44508,SO44508
44532,SO44532
Note:no need of sortorder Column ,thats y i necglected in output.
Any one please help on this..
Thanks in advance.
You can concatenate your result using + or CONCAT like this.
SELECT LTRIM(SalesPersonID) + ',' + LTRIM(PostalCode) + ISNULL(',' + LTRIM(City),'')
FROM CTE2
ORDER BY SortOrder
Complete Query
;WITH CTE
AS (
SELECT DISTINCT s.SalesPersonID
, CAST(A.PostalCode AS NVARCHAR(25)) AS PostalCode
, A.City
, CAST(s.SalesPersonID AS VARCHAR(MAX)) AS SortOrder
FROM Sales.SalesOrderHeader S(NOLOCK)
, Person.Person P(NOLOCK)
, Person.Address A(NOLOCK)
, #table t
WHERE s.SalesPersonID IS NOT NULL
AND S.SalesPersonID = P.BusinessEntityID
AND S.SalesPersonID = A.AddressID
AND S.SalesPersonID IN ('274')
UNION ALL
SELECT a.SalesOrderID
, a.SalesOrderNumber
, NULL
, C.SortOrder + CAST(a.SalesOrderID AS VARCHAR(MAX))
FROM CTE C
INNER JOIN Sales.SalesOrderHeader A(NOLOCK)
ON A.SalesPersonID = C.SalesPersonID
), CTE2 as
(
SELECT *
FROM cte
union all
select
cast ( P.BusinessEntityID as nvarchar(50)),
cast (P.NationalIDNumber as nvarchar(30)),
cast (P.Gender as nvarchar(20)),
cast (P.BusinessEntityID as VARCHAR(MAX)) + cast ('1' as VARCHAR(MAX))
from HumanResources.Employee P(nolock)
where exists(
select 1 from CTE C
where P.BusinessEntityID=C.SalesPersonID )
)
SELECT LTRIM(SalesPersonID) + ',' + LTRIM(PostalCode) + ISNULL(',' + LTRIM(City),'')
FROM CTE2
ORDER BY SortOrder
Create Proc [dbo].[SprptAssessmentCompartion_Subject]
#intQstnMasterID int,
#intAssessmentID int,
#intQstnMasterID1 int,
#intAssessmentID1 int,
#intUserID int
As
Begin
select DISTINCT vchSubject,intUserID,SUM(FrstId) as 'FrstId' ,SUM(ScndId) as 'ScndId' from
( SELECT
intSubjectID,
intUserID,
ISNULL([#intAssessmentID],0) as 'FrstId',
ISNULL([#intAssessmentID1],0) as 'ScndId',
FinalsCORE
FROM
(
select DISTINCT intSubjectID,intUserID,intAssignmnetID,SUM(KidTtl) as 'KidScore',COUNT(intSubjectID) AS 'FinalsCORE' ,(SUM(KidTtl) /COUNT(intSubjectID)*100) as 'Ct' from
(
select Answetble.vchAssignmentName ,intAssignmnetID,intUserID,intSlNo,isnull(QuiestionPaper.vchTopic,'-') as 'VchTopic',isnull(Answetble.fltMark,0) as 'KidTtl' ,QuiestionPaper.intSubjectID from QuiestionMapping
inner join QuiestionPaper on QuiestionPaper.intQstnID=QuiestionMapping.intQstnID
Left outer join
(
select distinct intQstnID,intAssessmentID,intAssignmnetID,intUserID,intQstnMasterID,fltMark,fltTotalMark,intAssignedByUserID,vchAssignmentName from
(
SELECT * from ManageAssessment
inner join Assignment ON Assignment.intAssignmnetID=ManageAssessment.intAssessmentID) as B
INNER JOIN UserMapping ON UserMapping.intPTUserID= intAssignedByUserID
where intQstnMasterID=#intQstnMasterID and intAssessmentID=#intAssessmentID AND intPTUserID=#intUserID
OR( intQstnMasterID=#intQstnMasterID1 and intAssessmentID=#intAssessmentID1 AND intPTUserID=#intUserID)
)
as Answetble on Answetble.intQstnID=QuiestionPaper.intQstnID
where QuiestionMapping.intQstnMasterID=#intQstnMasterID OR QuiestionMapping.intQstnMasterID=#intQstnMasterID1
)as A
GROUP BY intAssignmnetID,intSubjectID,intUserID
)
AS t
PIVOT
(
Max(Ct)
FOR intAssignmnetID IN( [#intAssessmentID] ,[#intAssessmentID1])
) AS p
)as B
inner join subject on Subject.intSubjectID=b.intSubjectID
group by subject.vchSubject,B.intUserID
End
Here #intAssessmentID is one of the columns when I use this in stored procedure I will get error
Msg 8114, Level 16, State 1, Procedure SprptAssessmentCompartion_Subject, Line 47
Error converting data type nvarchar to int.
Msg 473, Level 16, State 1, Procedure SprptAssessmentCompartion_Subject, Line 47
The incorrect value "#intAssessmentID" is supplied in the PIVOT operator.
Can anyone help me to resolve the error?
You cannot specify columns for PIVOT this way, you have to use dynamic SQL.
Create Proc [dbo].[SprptAssessmentCompartion_Subject]
#intQstnMasterID int,
#intAssessmentID int,
#intQstnMasterID1 int,
#intAssessmentID1 int,
#intUserID int
As
Begin
declare #sql as nvarchar(max) = N'select DISTINCT vchSubject,intUserID,SUM(FrstId) as ''FrstId'' ,SUM(ScndId) as ''ScndId'' from
( SELECT
intSubjectID,
intUserID,
ISNULL([' + CONVERT(NVARCHAR(20), #intAssessmentID) + N'],0) as ''FrstId'',
ISNULL([' + CONVERT(NVARCHAR(20), #intAssessmentID1) + N'],0) as ''ScndId'',
FinalsCORE
FROM
(
select DISTINCT intSubjectID,intUserID,intAssignmnetID,SUM(KidTtl) as ''KidScore'',COUNT(intSubjectID) AS ''FinalsCORE'' ,(SUM(KidTtl) /COUNT(intSubjectID)*100) as ''Ct'' from
(
select Answetble.vchAssignmentName ,intAssignmnetID,intUserID,intSlNo,isnull(QuiestionPaper.vchTopic,''-'') as ''VchTopic'',isnull(Answetble.fltMark,0) as ''KidTtl'' ,QuiestionPaper.intSubjectID from QuiestionMapping
inner join QuiestionPaper on QuiestionPaper.intQstnID=QuiestionMapping.intQstnID
Left outer join
(
select distinct intQstnID,intAssessmentID,intAssignmnetID,intUserID,intQstnMasterID,fltMark,fltTotalMark,intAssignedByUserID,vchAssignmentName from
(
SELECT * from ManageAssessment
inner join Assignment ON Assignment.intAssignmnetID=ManageAssessment.intAssessmentID) as B
INNER JOIN UserMapping ON UserMapping.intPTUserID= intAssignedByUserID
where intQstnMasterID=#intQstnMasterID and intAssessmentID=#intAssessmentID AND intPTUserID=#intUserID
OR( intQstnMasterID=#intQstnMasterID1 and intAssessmentID=#intAssessmentID1 AND intPTUserID=#intUserID)
)
as Answetble on Answetble.intQstnID=QuiestionPaper.intQstnID
where QuiestionMapping.intQstnMasterID=#intQstnMasterID OR QuiestionMapping.intQstnMasterID=#intQstnMasterID1
)as A
GROUP BY intAssignmnetID,intSubjectID,intUserID
)
AS t
PIVOT
(
Max(Ct)
FOR intAssignmnetID IN( [' + CONVERT(NVARCHAR(20), #intAssessmentID) + N'] ,[' + CONVERT(NVARCHAR(20), #intAssessmentID1) + N'])
) AS p
)as B
inner join subject on Subject.intSubjectID=b.intSubjectID
group by subject.vchSubject,B.intUserID'
exec sp_executesql #sql
End
I am working with the following query.I want to use Date_Sent_to_Recorder in my other calculations which follows.I am getting an error "Invalid column name 'Date_Sent_to_Recorder'." People recommended using a CTE for this but i am not able to fit it in this scenerio.I have a correlated subquery which calculates Date_Sent_to_Recorder.Please help.
SELECT
C.Name Client ,
SecONdary_Document.Primary_Document_ID ,
SecONdary_Document.Secondary_Document_Id ,
Primary_Document.State + ',' + GB_Counties.CountyName State ,
Grantor.Name Grantor ,
Loan_Number ,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date ,
( SELECT CASE WHEN dbo.SECONDARY_DOCUMENT.Status_ID = 21
THEN CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT.Updated_Dt, 101)
ELSE ( SELECT TOP 1
CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt, 101)
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Secondary_Document_ID = SecONdary_Document.Secondary_Document_Id
AND SECONDARY_DOCUMENT_STATUS_HISTORY.Status_ID = 21
ORDER BY dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt DESC
)
END
) AS Date_Sent_to_Recorder ,
Satis_TimeFrame ,
CASE WHEN PIF_Date IS NULL
OR Date_Sent_to_Recorder IS NULL THEN NULL
ELSE DATEDIFF(DAY, PIF_Date,
Date_Sent_to_Recorder)
END TotalDays ,
CASE WHEN PIF_Date IS NULL
OR Date_Sent_to_Recorder IS NULL THEN NULL
ELSE CASE WHEN DATEDIFF(DAY, PIF_Date,
ISNULL(Date_Sent_to_Recorder,
GETDATE())) > Satis_TimeFrame
THEN 'N'
ELSE 'Y'
END
END InCompliance ,
Loan_Name ,
Deal_Name ,
Deal.Deal_Id ,
Loan.Loan_Id
FROM Primary_Document
INNER JOIN SecONdary_Document ON SecONdary_Document.Primary_Document_ID = Primary_Document.Primary_Document_ID
INNER JOIN Status ON Status.Status_Id = SecONdary_Document.Status_Id
INNER JOIN GB_Counties ON GB_Counties.CountyId = Primary_Document.County_Id
INNER JOIN Loan ON Loan.Loan_Id = Primary_Document.Loan_Id
EDIT------------
DECLARE #Date_Sent_to_Recorder varchar(10)
SELECT C.Name Client ,
SecONdary_Document.Primary_Document_ID ,
SecONdary_Document.Secondary_Document_Id ,
Primary_Document.State + ',' + GB_Counties.CountyName State ,
Grantor.Name Grantor ,
Loan_Number ,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date ,
--<START>
--3021,RRaghuvansi,If current status is 21 in SECONDARY_DOCUMENT then take Updated_Dt else take Created_Dt in SECONDARY_DOCUMENT_STATUS_HISTORY with status Out For Recorder
--CONVERT(VARCHAR(20), Recording_Date, 101) AS Recording_Date ,
#Date_Sent_to_Recorder=[dbo].[GET_RecordingDate](SecONdary_Document.Secondary_Document_Id), --<END>
Satis_TimeFrame ,
Loan_Name ,
Deal_Name ,
Deal.Deal_Id ,
Loan.Loan_Id
FROM Primary_Document
Since your schema is sort of unclear, here is a brief sample for the derived table syntax and referencing values from the derived table
Declare #Sample table(id1 int, id2 int, value varchar(20))
insert into #sample values (1,1, 'this')
insert into #sample values(2,2, 'that')
insert into #sample values(3,2, 'the other')
Select t1.ID1, t1.Value, t2.RevVal,
case
when t2.RevVal = 'siht' then 1 else 0
end as RevIsThisBackwards
from #sample t1
inner join (Select id1, reverse(value) as RevVal from #sample) t2
on t1.ID1 = t2.ID1
Results
id VALUES Rev Rev Value is this backwards
1 this siht 1
2 that taht 0
3 the other rehto eht 0
So you'll want to move the calculated column, and sufficient columns to join to into a derived table, in your case it would it would look similar to the below
INNER JOIN Loan ON Loan.Loan_Id = Primary_Document.Loan_Id
INNER JOIN (Select SomPKField, CASE WHEN dbo.SECONDARY_DOCUMENT.Status_ID = 21
THEN CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT.Updated_Dt, 101)
ELSE ( SELECT TOP 1
CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt, 101)
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE
dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Secondary_Document_ID = SecONdary_Document.Secondary_Document_Id
AND SECONDARY_DOCUMENT_STATUS_HISTORY.Status_ID = 21
ORDER BY dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt DESC
)
END as Date_Sent_to_Recorder
) as Sub1
on SomeTable.SomePKField = Sub1.SomePKField
**I edit your edit in this edit.**
SELECT C.Name Client ,
SecONdary_Document.Primary_Document_ID ,
SecONdary_Document.Secondary_Document_Id ,
Primary_Document.State + ','
+ GB_Counties.CountyName State ,
Grantor.Name Grantor ,
Loan_Number ,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date ,
[dbo].[GET_RecordingDate]
(SecONdary_Document.Secondary_Document_Id)
As Date_Sent_To_Recorder
Satis_TimeFrame ,
Loan_Name ,
Deal_Name ,
Deal.Deal_Id ,
Loan.Loan_Id
FROM Primary_Document
You cannot refer to a computed column in other columns of a SELECT. The simplest solution for what you are trying to achieve is to pre-calculate Date_Sent_to_Recorder and store it in a temporary table, then join to that table when doing your main query.
Protip: use proper formatting and table aliases; SQL like you posted is difficult to read, and almost impossible to understand.
Edit: something like this:
create table #temp
( Primary_Document_ID int,
Date_Sent_To_Recorder datetime )
insert #temp
select Primary_Document_ID,
CASE
WHEN dbo.SECONDARY_DOCUMENT.Status_ID = 21
THEN CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT.Updated_Dt, 101)
ELSE
(SELECT TOP 1
CONVERT(VARCHAR(10), dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt, 101)
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Secondary_Document_ID = SecONdary_Document.Secondary_Document_Id
AND SECONDARY_DOCUMENT_STATUS_HISTORY.Status_ID = 21
ORDER BY dbo.SECONDARY_DOCUMENT_STATUS_HISTORY.Created_Dt DESC)
END
from SecONdary_Document
-- main select, joining to #temp
Because Date_Sent_to_Recorder depends only on SECONDARY_DOCUMENT & SECONDARY_DOCUMENT_STATUS_HISTORY tables, you can replace SECONDARY_DOCUMENT in the INNER JOIN by the following (which gives you Date_Sent_to_Recorder as a column):
SELECT SD.Primary_Document_ID,
SD.Secondary_Document_Id,
CASE WHEN SD.Status_ID = 21
THEN CONVERT(VARCHAR(10), SD.Updated_Dt, 101)
ELSE CONVERT(VARCHAR(10), SDSH.Created_Dt, 101)
END Date_Sent_to_Recorder
FROM SECONDARY_DOCUMENT SD
INNER JOIN dbo.SECONDARY_DOCUMENT_STATUS_HISTORY SDSH
ON SDSH.Secondary_Document_ID = SD.Secondary_Document_Id
AND SDSH.Status_ID = 21
INNER JOIN (SELECT Secondary_Document_ID, max(Created_Dt) Created_Dt
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE Status_ID = 21
GROUP BY Secondary_Document_ID) SDSH2
ON SDSH.Secondary_Document_ID = SDSH2.Secondary_Document_Id
AND SDSH.Created_Dt = SDSH2.Created_Dt
and finally you have:
SELECT C.Name Client,
SecONdary_Document.Primary_Document_ID,
SecONdary_Document.Secondary_Document_Id,
Primary_Document.State + ',' + GB_Counties.CountyName State,
Grantor.Name Grantor,
Loan_Number,
CONVERT(VARCHAR(10), Primary_Document.PIF_Date, 101) PIF_Date,
SecONdary_Document.Date_Sent_to_Recorder,
Satis_TimeFrame,
CASE WHEN PIF_Date IS NULL
OR SecONdary_Document.Date_Sent_to_Recorder IS NULL
THEN NULL
ELSE DATEDIFF(DAY, PIF_Date,
SecONdary_Document.Date_Sent_to_Recorder)
END TotalDays,
CASE WHEN PIF_Date IS NULL
OR SecONdary_Document.Date_Sent_to_Recorder IS NULL THEN NULL
ELSE CASE WHEN DATEDIFF(DAY, PIF_Date,
ISNULL(SecONdary_Document.Date_Sent_to_Recorder
,GETDATE())) > Satis_TimeFrame
THEN 'N'
ELSE 'Y'
END
END InCompliance,
Loan_Name,
Deal_Name,
Deal.Deal_Id,
Loan.Loan_Id
FROM Primary_Document
INNER JOIN (SELECT SD.Primary_Document_ID,
SD.Secondary_Document_Id,
CASE WHEN SD.Status_ID = 21
THEN CONVERT(VARCHAR(10), SD.Updated_Dt, 101)
ELSE CONVERT(VARCHAR(10), SDSH.Created_Dt, 101)
END Date_Sent_to_Recorder
FROM SECONDARY_DOCUMENT SD
INNER JOIN dbo.SECONDARY_DOCUMENT_STATUS_HISTORY SDSH
ON SDSH.Secondary_Document_ID = SD.Secondary_Document_Id
AND SDSH.Status_ID = 21
INNER JOIN (SELECT Secondary_Document_ID, max(Created_Dt) Created_Dt
FROM dbo.SECONDARY_DOCUMENT_STATUS_HISTORY
WHERE Status_ID = 21
GROUP BY Secondary_Document_ID) SDSH2
ON SDSH.Secondary_Document_ID = SDSH2.Secondary_Document_Id
AND SDSH.Created_Dt = SDSH2.Created_Dt) SecONdary_Document
ON SecONdary_Document.Primary_Document_ID
= Primary_Document.Primary_Document_ID
INNER JOIN Status ON Status.Status_Id = SecONdary_Document.Status_Id
INNER JOIN GB_Counties ON GB_Counties.CountyId = Primary_Document.County_Id
INNER JOIN Loan ON Loan.Loan_Id = Primary_Document.Loan_Id