Syntax for a SQL query - sql

k=conn:query({live=true,sql ="select DISTINCT O.OrderId, (SELECT R.ReportBody + (char(13)+char(10)) + 'Modified By: ' + UM.FirstName + ' at ' + UM.LastName + (char(13)+char(10)) +'Authored By: ' + UC.FirstName + ' at ' + UC.LastName + (char(13)+char(10)) + (char(13)+char(10)) AS [text()] FROM dbo.OrderReports R INNER JOIN dbo.Users UM ON R.ModifiedById = UM.UserId INNER JOIN dbo.Users UC ON R.CreatedById = UC.UserId WHERE R.OrderId = M[1].OrderId ORDER BY R.CreateDate DESC FOR XML PATH('')) 'OrderReport'FROM dbo.Orders O "})
I have above mentioned query and I am getting incorrect syntax error at where R.OrderId = M[1].OrderId , I am using sql with Lua.
P.S: The value in M[1].OrderId is a uniqueidentifier.
But if I have this query:
mk = conn:query({live = true, sql= "select ReportBody,DENSE_RANK() over (Order by ModifyDate DESC) from OrderReports where OrderId = '"..M[1].OrderId.."'"})
It works with M[1].OrderId though M[1].OrderId gives syntax error in the first query. How can I fix this in first query?

OK, you have not answered my last question. But assuming that the query you have written is working this is what you are after:
k=conn:query({live=true,sql ="select DISTINCT O.OrderId, (SELECT R.ReportBody + (char(13)+char(10)) + 'Modified By: ' + UM.FirstName + ' at ' + UM.LastName + (char(13)+char(10)) +'Authored By: ' + UC.FirstName + ' at ' + UC.LastName + (char(13)+char(10)) + (char(13)+char(10)) AS [text()] FROM dbo.OrderReports R INNER JOIN dbo.Users UM ON R.ModifiedById = UM.UserId INNER JOIN dbo.Users UC ON R.CreatedById = UC.UserId WHERE R.OrderId = '"..M[1].OrderId.."' ORDER BY R.CreateDate DESC FOR XML PATH('')) 'OrderReport'FROM dbo.Orders O "})

Related

Find paths from one table to another over keys

For example;
I have 500 tables in database. One table is named "Table1" and another "Table234". I need to join "Table1" and "Table234" but I can't join them directly, I need to use other tables. Is it possible to make query where I enter starting table (in this case Table1) and ending table (in this case Table234) and it finds all possible paths over keys from starting to ending table.
Let's say that I have two possible paths:
Table1 -> Table 23 -> Table456 -> Table234
Table1 -> Table 34 -> Table23 -> Zable 456 -> Table234
Select * from table1
join table23 on XX = XX
join table456 on XX = XX
join table234 on XX = XX
Maybe something like BFS to find shortest path, and than save it somewhere and find BFS without that path?
Solution (#Geoff Patterson):
IF OBJECT_ID('tempdb..#paths') IS NOT NULL
DROP TABLE #paths
IF OBJECT_ID('tempdb..#shortestPaths') IS NOT NULL
DROP TABLE #shortestPaths
GO
DECLARE #targetObjectName SYSNAME = 'YourTableNameHere'
;WITH singleColumnFkColumns AS (
SELECT fk1.*
FROM sys.foreign_key_columns fk1
LEFT JOIN sys.foreign_key_columns fk2 ON fk2.constraint_object_id = fk1.constraint_object_id AND fk2.constraint_column_id = 2
WHERE fk1.constraint_column_id = 1
AND fk2.constraint_object_id IS NULL
)
, parentCTE AS (
SELECT
p.object_id AS ParentId
,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable
,pc.column_id AS ParentColumnId
,pc.name AS ParentColumn
,r.object_id AS ChildId
,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable
,rc.column_id AS ChildColumnId
,rc.name AS ChildColumn
,1 AS depth
, ',' + CONVERT(VARCHAR(MAX), p.object_id) + '_NULL_' + CONVERT(VARCHAR(MAX), pc.column_id) +
',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath
FROM sys.foreign_key_columns fk
JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id
JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id
JOIN sys.tables p ON p.object_id = fk.parent_object_id
JOIN sys.tables r ON r.object_id = fk.referenced_object_id
WHERE fk.parent_object_id = OBJECT_ID(#targetObjectName)
AND p.object_id <> r.object_id
UNION ALL
SELECT
p.object_id AS ParentId
,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable
,pc.column_id AS ParentColumnId
,pc.name AS ParentColumn
,r.object_id AS ChildId
,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable
,rc.column_id AS ChildColumnId
,rc.name AS ChildColumn
,cte.depth + 1 AS depth
,cte.TraversalPath + ',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath
FROM parentCTE cte
JOIN singleColumnFkColumns fk
ON fk.parent_object_id = cte.ChildId
JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id
JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id
JOIN sys.tables p ON p.object_id = fk.parent_object_id
JOIN sys.tables r ON r.object_id = fk.referenced_object_id
WHERE p.object_id <> r.object_id
AND cte.TraversalPath NOT LIKE ('%_' + CONVERT(VARCHAR(MAX), r.object_id) + '%')
)
SELECT *
INTO #paths
FROM parentCTE
ORDER BY depth, ParentTable, ChildTable
GO
SELECT *
INTO #shortestPaths
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY ChildTable ORDER BY depth ASC) AS rankToThisChild
FROM #paths
) x
WHERE rankToThisChild = 1
ORDER BY ChildTable
GO
WITH joinCTE AS (
SELECT p.ChildTable
, p.TraversalPath AS ParentTraversalPath
, NULL AS depth
, CONVERT(VARCHAR(MAX), 'FROM ' + p.ChildTable + ' t' + CONVERT(VARCHAR(MAX), p.depth+1)) AS JoinString
FROM #shortestPaths p
UNION ALL
SELECT cte.ChildTable
, REPLACE(p.TraversalPath, ',' + CONVERT(VARCHAR, p.ChildId) + '_' + CONVERT(VARCHAR, p.ParentColumnId)+ '_' + CONVERT(VARCHAR, p.ChildColumnId), '') AS TraversalPath
, p.depth
, cte.JoinString + '
' + CONVERT(VARCHAR(MAX), 'JOIN ' + p.ParentTable + ' t' + CONVERT(VARCHAR(MAX), p.depth) + ' ON t' + CONVERT(VARCHAR(MAX), p.depth) + '.' + p.ParentColumn + ' = t' + CONVERT(VARCHAR(MAX), p.depth+1) + '.' + p.ChildColumn) AS JoinString
FROM joinCTE cte
JOIN #paths p
ON p.TraversalPath = cte.ParentTraversalPath
)
SELECT ChildTable, 'SELECT TOP 100 *
' +JoinString
FROM joinCTE
WHERE depth = 1
ORDER BY ChildTable
GO
You can replace "YourTableNameHere" in script and it will find You all links to from any to that table.
And in my JAVA software looks like:
RS = CALIzb.main(Conn, "IF OBJECT_ID('tempdb..#paths') IS NOT NULL DROP TABLE #paths IF OBJECT_ID('tempdb..#shortestPaths') IS NOT NULL DROP TABLE #shortestPaths DECLARE #targetObjectName SYSNAME = '"+txtTablica.getText().trim()+"' ;WITH singleColumnFkColumns AS ( SELECT fk1.* FROM sys.foreign_key_columns fk1 LEFT JOIN sys.foreign_key_columns fk2 ON fk2.constraint_object_id = fk1.constraint_object_id AND fk2.constraint_column_id = 2 WHERE fk1.constraint_column_id = 1 AND fk2.constraint_object_id IS NULL ), parentCTE AS ( SELECT p.object_id AS ParentId ,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable,pc.column_id AS ParentColumnId,pc.name AS ParentColumn,r.object_id AS ChildId,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable,rc.column_id AS ChildColumnId,rc.name AS ChildColumn,1 AS depth, ',' + CONVERT(VARCHAR(MAX), p.object_id) + '_NULL_' + CONVERT(VARCHAR(MAX), pc.column_id) +',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath FROM sys.foreign_key_columns fk JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id JOIN sys.tables p ON p.object_id = fk.parent_object_id JOIN sys.tables r ON r.object_id = fk.referenced_object_id WHERE fk.parent_object_id = OBJECT_ID(#targetObjectName) AND p.object_id <> r.object_id UNION ALL SELECT p.object_id AS ParentId,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable,pc.column_id AS ParentColumnId,pc.name AS ParentColumn,r.object_id AS ChildId,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable,rc.column_id AS ChildColumnId,rc.name AS ChildColumn,cte.depth + 1 AS depth,cte.TraversalPath + ',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath FROM parentCTE cte JOIN singleColumnFkColumns fk ON fk.parent_object_id = cte.ChildId JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id JOIN sys.tables p ON p.object_id = fk.parent_object_id JOIN sys.tables r ON r.object_id = fk.referenced_object_id WHERE p.object_id <> r.object_id AND cte.TraversalPath NOT LIKE ('%_' + CONVERT(VARCHAR(MAX), r.object_id) + '%')) SELECT * INTO #paths FROM parentCTE ORDER BY depth, ParentTable, ChildTable SELECT * INTO #shortestPaths FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ChildTable ORDER BY depth ASC) AS rankToThisChild FROM #paths) x WHERE rankToThisChild = 1 ORDER BY ChildTable");
RS = CALIzb.main(Conn, "WITH joinCTE AS ( SELECT p.ChildTable, p.TraversalPath AS ParentTraversalPath, NULL AS depth, CONVERT(VARCHAR(MAX), 'FROM ' + p.ChildTable + ' t' + CONVERT(VARCHAR(MAX), p.depth+1)) AS JoinString FROM #shortestPaths p UNION ALL SELECT cte.ChildTable, REPLACE(p.TraversalPath, ',' + CONVERT(VARCHAR, p.ChildId) + '_' + CONVERT(VARCHAR, p.ParentColumnId)+ '_' + CONVERT(VARCHAR, p.ChildColumnId), '') AS TraversalPath, p.depth, cte.JoinString + ' ' + CONVERT(VARCHAR(MAX), 'JOIN ' + p.ParentTable + ' t' + CONVERT(VARCHAR(MAX), p.depth) + ' ON t' + CONVERT(VARCHAR(MAX), p.depth) + '.' + p.ParentColumn + ' = t' + CONVERT(VARCHAR(MAX), p.depth+1) + '.' + p.ChildColumn) AS JoinString FROM joinCTE cte JOIN #paths p ON p.TraversalPath = cte.ParentTraversalPath) SELECT ChildTable, 'SELECT TOP 100 * ' +JoinString FROM joinCTE WHERE depth = 1 ORDER BY ChildTable");
vezaKljuceva.setModel(DbUtils.resultSetToTableModel(RS));

Adding order by for XML throws error

Here is my actual query
SELECT
aces.ProductID,'<p>' +
Replace(STUFF((SELECT DISTINCT ', ' + CAST(A.year AS VARCHAR(4)) + ' ' + A.make + ' ' + A.model + ' ' + A.enginebase_new
FROM ACES_Data A
WHERE A.ProductID = aces.ProductID
FOR XML PATH('')), 1, 1, ''), ',', '<br>')
+ '</p><p>' + i.[Subline Code] + '<br>' + i.[Subline Name] + '</p>' AS FullDescription
FROM
ACES_Data aces
LEFT OUTER JOIN
InventoryPricing i ON aces.part_number = i.PART
WHERE
aces.ProductID IS NOT NULL
AND aces.MakeModelMappingID IS NOT NULL
GROUP BY
aces.ProductID, i.[Part Description], i.[Subline Code], i.[Subline Name]
Now adding order by before XML throws an error.
Please look below updated query
SELECT
aces.ProductID,'<p>' +
Replace(
STUFF
(
(
SELECT
distinct ', ' + Cast(A.year as varchar(4)) + ' ' + A.make +' ' + A.model + ' ' + A.enginebase_new
FROM
ACES_Data A
Where
A.ProductID=aces.ProductID
order by A.make,A.year asc
FOR XML PATH('')
),1,1,'')
,',',
'<br>'
)
+ '</p><p>' + i.[Subline Code] + '<br>'+ i.[Subline Name] + '</p>' As FullDescription
from ACES_Data aces
Left outer join InventoryPricing i
on aces.part_number = i.PART
where aces.ProductID is not null
and aces.MakeModelMappingID is not null
Group By aces.ProductID,i.[Part Description],i.[Subline Code],i.[Subline Name]
on inserting
Where A.ProductID=aces.ProductID **order by A.make,A.year asc** FOR XML PATH('')
it gives me error as
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
Since enginebase_new & model is not part of Order by you cannot use DISTINCT in Select.
Use Group by instead of DISTINCT to remove duplicates
SELECT ', ' + Cast(A.year AS VARCHAR(4)) + ' ' + A.make
+ ' ' + A.model + ' ' + A.enginebase_new
FROM ACES_Data A
WHERE A.ProductID = aces.ProductID
GROUP BY A.year,
A.make,
A.model,
A.enginebase_new
ORDER BY A.make,
A.year ASC
FOR XML PATH('')

Get specific columns from xml path

I have this query here:
SELECT
T.AKSIONERET,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
I need to retrieve, instead of T.AKSIONERET the FullAksionerCitizenship which I get from the for xml path.
I know I have to do some other SELECT but I kept getting errors, syntax errors.
Could someone help?
Thanks in advance
I'm quite sure, that there could be a better design and I'm not able to run this against test data off course, but this could work:
SELECT
T.AKSIONERET,
T2.FullAksionerCitizenship,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
--here starts the new block (difficult for me without knowing your db...)
LEFT JOIN
(SELECT
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
) AS FullAksionerCitizenship
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T2 ON T2.Subject_DEF_Code = SD.SUBJECT_DEF_CODE

attempt to index global variable OE (a nil value) Lua with sql

mk = conn:query({live = true, sql = "SELECT DISTINCT OE.OderNumber,(SELECT R.ReportBody + ' CRLF ' +'Modified By: ' + UM.FirstName + ' at ' + UM.LastName + ' CRLF '+ 'Authored By: ' + UC.FirstName + ' at ' + UC.LastName + ' CRLF ' +'CRLF' AS [text()] FROM dbo.OrderReports R INNER JOIN dbo.Orders O ON R.OrderId = O.OrderId INNER JOIN dbo.Users UM ON R.ModifiedById = UM.UserId INNER JOIN dbo.Users UC ON R.CreatedById = UC.UserId WHERE O.OrderNumber = '"..OE.OderNumber.."' ORDER BY R.CreateDateFOR XML PATH('')) 'OrderReport' FROM dbo.vw_OrderLevelEvents OE"})
This query works just fine in SQL but while I have it with Lua, it says attempt to index global variable OE(a nil value)
How can i fix this
From your code :
WHERE O.OrderNumber = '"..OE.OderNumber.."' ORDER BY R.CreateDateFOR
Here you're using the OderNumber key of the OE table and its value is nil. You'll need to fix that before using its key.
EDIT : you really should rename it to OrderNumber, too! ;)

Store procedure for a select statement which should take input

Can anyone please help me with the store procedure for the following
select statement which should take an input of completeddatekey which
is at the bottom of the select statement
CompletedDateKey is filled with a key in this code but I need a store procedure that should take an input of completeddatekey
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
Its really simple. Just create procedure like below
create procedure MyProc(
#CompletedDateKey varchar(20) )
as
Begin
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = #CompletedDateKey
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
End
Execute it like
Execute MyProc '20140131'