Select a column from a different table in SQL Server - sql

I would like to be able to select the column pa.NumberOfPages from dm_package pa in the following select statement. How can I do this?
Select statement 1
SELECT
Case When IsPackage = 1 then 'DM, Package' else 'DM' end as FaxType,
FaxId, RequestDate, FaxedTo, FaxNumber, Status, ExtendedStatus, StatusDate,
UserName, IsPackage, DocumentId, -1 as PatientMedicationId, '' as Event,
'-1' as NCPDPID, 0 as IsEPerscription, -1 as AccessionNumber,
Case When IsPackage = 0 then
(Select FilePath from PatientDocument where DocumentId = fl.DocumentId and ( '443' = -1 or '443' = PatientId ))
else (Select FilePath from dm_Package where fl.DocumentId = PackageId and ( '443' = -1 or '443' = PatientId )) End as Path,
Case When IsPackage = 0 then
(Select LastFirstName from Patient p, PatientDocument pd where fl.DocumentId = pd.DocumentId and pd.PatientId = p.PatientId)
else (select LastFirstName from Patient p, dm_Package pa where fl.DocumentId = pa.PackageId and pa.PatientId = p.PatientId) END as LastFirstName,
Case When IsPackage = 0 then
(select [Description] from PatientDocument where fl.DocumentId = DocumentId and ( '443' = -1 or '443' = PatientId ))
else (select PackageName from dm_Package where fl.DocumentId = PackageId and ( '443' = -1 or '443' = PatientId )) End as [Description],
'' as JobId, -1 as SeqNumber, '' as RefNumber, (select DocId from dbo.PatientDocument pd where fl.DocumentId = pd.DocumentId) as DocId
FROM dbo.dm_FaxLog fl
Table name dm_package pa
pa.IsFax, pa.FaxName, pa.faxNumber, pa.FilePath, pa.DocRoot, pa.Note, pa.PatientId,
isnull(fl.ExtendedStatus,'') as FaxExtendedStatus, StatusDate as FaxStatusDate, pa.DocId, pa.NumberOfPages

Are you familiar with how to join tables in SQL?
http://technet.microsoft.com/en-us/library/ms191517(v=sql.105).aspx
select a.data1, b.data2
from a_table a
join b_table b on a.data3 = b.data3

I assume FaxNumber in dm_FaxLog and dm_package are same. Then you can do -
SELECT f1.faxNumber, pa.NumberOfPages --list other required columns
FROM dm_FaxLog fl
INNER JOIN dm_package pa ON pa.faxNumber = f1.faxNumber

Related

Procedure showing an error related to merge in sql and please verify that overall code is fine or not

Code is showing an error
Merge statements with a WHEN NOT MATCHED [BY TARGET] clause must target a hash distributed table
Also please verify that the overall syntax is fine or not?
MERGE IR_CREDITREQUEST_SPTESTING AS T
USING (
SELECT
TT.TaxYear
,TT.TaxPayerSSN
,TT.EngagementID
,TT.CreditRequestType
,TT.BorrowerID
,TT.NameSuffix
,TT.FirstName
,TT.MiddleName
,TT.LastName
,TT.SpouseName
,TT.SpouseSSN
,TT.PrintPositionType
,TT.MaritalStatusType
,TT.StreetAddress
,TT.City
,TT.State
,TT.PostalCode
,TT.Type
,TT.Value
,TT.RequestDateTime
,TT.CreatedDateTime
,TT.RequestProcessed
,TT.BorrowerResidencyType
,TT.isActive
FROM
IR_CREDITREQUEST_SPTESTING TT
INNER JOIN (
select DISTINCT
A.TaxYear,
A.[TaxPayer-SSN] AS TaxPayerSSN,
A.EngagementID AS EngagementID,
CASE
WHEN A.[Filing Status] = 'MFJ' THEN 'Joint'
ELSE A.[Filing Status]
END AS [CreditRequestType],
'' AS BorrowerID ,
A.[TaxPayer-Title/Suffix] AS NameSuffix,
A.[TaxPayer-FirstName] AS FirstName,
'' AS MiddleName,
A.[TaxPayer-LastName] AS LastName,
B.[Spouse-FirstName] + ' ' + B.[Spouse-LastName] AS [SpouseName],
B.[Spouse-SSN] AS [SpouseSSN],
CASE
WHEN A.[Filing Status] = 'MFJ' THEN 'CoBorrower'
WHEN A.[Filing Status] = 'Single' THEN 'Borrower'
ELSE A.[Filing Status]
END AS [PrintPositionType],
CASE
WHEN B.[Spouse-FirstName] IS not null THEN 'Married'
ELSE 'Unmarried'
END AS [MaritalStatusType],
C.[Address] AS StreetAddress,
C.City AS City,
C.[State] AS State,
C.[Postal Code] AS PostalCode,
A.[Primary Contact] AS Type,
A.[TaxPayer-Home/Evening Telephone Number] AS Value,
NULL AS RequestDateTime,
GETDATE() AS CreatedDateTime,
NULL AS RequestProcessed,
NULL AS BorrowerResidencyType,
0 AS IsActive
from DimTaxPayerInfo A
LEFT join DimTaxPayerSpouseInfo B on A.[TaxPayer-SSN] = B.[TaxPayer-SSN] AND B.TaxSoftwareId = 4
LEFT join stg.stg_DimTaxPayerAddress C on A.[TaxPayer-SSN] = C.[TaxPayer-SSN]
WHERE A.[TaxPayer-SSN] != ''
) as Y
ON TT.[EngagementID] = Y.[EngagementID]
) DD
ON T.[EngagementID] = DD.[EngagementID]
WHEN MATCHED THEN
Update
SET T.TaxYear = DD.TaxYear
,T.TaxPayerSSN = dd.TaxPayerSSN
,T.EngagementID = dd.EngagementID
,T.CreditRequestType = dd.CreditRequestType
,T.BorrowerID = dd.BorrowerID
,T.NameSuffix = dd.NameSuffix
,T.FirstName = dd.FirstName
,T.MiddleName = dd.MiddleName
,T.LastName = dd.LastName
,T.SpouseName = dd.SpouseName
,T.SpouseSSN = dd.SpouseSSN
,T.PrintPositionType = dd.PrintPositionType
,T.MaritalStatusType = dd.MaritalStatusType
,T.StreetAddress = dd.StreetAddress
,T.City = dd.City
,T.State = dd.State
,T.PostalCode = dd.PostalCode
,T.Type = dd.Type
,T.Value = dd.Value
,T.RequestDateTime = dd.RequestDateTime
,T.CreatedDateTime = dd.CreatedDateTime
,T.RequestProcessed = dd.RequestProcessed
,T.BorrowerResidencyType = dd.BorrowerResidencyType
,T.IsActive = dd.IsActive
WHEN NOT MATCHED THEN
INSERT
( TaxYear
,TaxPayerSSN
,EngagementID
,CreditRequestType
,BorrowerID
,NameSuffix
,FirstName
,MiddleName
,LastName
,SpouseName
,SpouseSSN
,PrintPositionType
,MaritalStatusType
,StreetAddress
,City
,State
,PostalCode
,Type
,Value
,RequestDateTime
,CreatedDateTime
,RequestProcessed
,BorrowerResidencyType
,IsActive
)
values (
dd.TaxYear
,dd.TaxPayerSSN
,dd.EngagementID
,dd.CreditRequestType
,dd.BorrowerID
,dd.NameSuffix
,dd.FirstName
,dd.MiddleName
,dd.LastName
,dd.SpouseName
,dd.SpouseSSN
,dd.PrintPositionType
,dd.MaritalStatusType
,dd.StreetAddress
,dd.City
,dd.State
,dd.PostalCode
,dd.Type
,dd.Value
,dd.RequestDateTime
,dd.CreatedDateTime
,dd.RequestProcessed
,dd.BorrowerResidencyType
,dd.IsActive
);
Your Merge Statement looks correct. This error is mostly seen in Azure Synapse. Make sure your target table is hash distributed to avoid this error.
Refer to the answer posted in the thread for a similar error.

SQL Query - How to suppress repeating values in the result set?

I'm trying to suppress the repeating values in TotalCarton column. Have tried to replace the value either blank or null but went failed. Any help?
Here is the SQL Script:
SELECT ORDERS.StorerKey,
ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = ( CASE BAX_PACK_DTL.PackType WHEN 'C' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
TotalPallet = ( CASE BAX_PACK_DTL.PackType WHEN 'P' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'C' AND PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'P' AND PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM ORDERS WITH (NOLOCK) INNER JOIN ORDERDETAIL WITH (NOLOCK) ON ORDERS.StorerKey = ORDERDETAIL.StorerKey
AND ORDERS.OrderKey = ORDERDETAIL.OrderKey
INNER JOIN PICKDETAIL WITH (NOLOCK) ON ORDERDETAIL.StorerKey = PICKDETAIL.StorerKey
AND ORDERDETAIL.OrderKey = PICKDETAIL.OrderKey
AND ORDERDETAIL.OrderLineNumber = PICKDETAIL.OrderLineNumber
INNER JOIN BAX_PACK_DTL WITH (NOLOCK) ON PICKDETAIL.OrderKey = BAX_PACK_DTL.OrderKey
AND PICKDETAIL.PickDetailKey = BAX_PACK_DTL.PickDetailKey
WHERE (SELECT COUNT(DISTINCT(ORDERKEY)) FROM PICKDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey ) > 0
AND BAX_PACK_DTL.PackKey = '0000000211'
AND BAX_PACK_DTL.OuterPackID IN
('P111111111',
'P22222222',
'P33333333')
GROUP BY ORDERS.StorerKey,
ORDERS.OrderKey,
ORDERS.ExternOrderKey,
ORDERS.HAWB,
ORDERS.SO,
ORDERS.EditWho,
ORDERS.AddDate,
PICKDETAIL.WaveKey,
BAX_PACK_DTL.OuterPackID,
BAX_PACK_DTL.PackKey,
BAX_PACK_DTL.PackType
ORDER BY BAX_PACK_DTL.OuterPackID ASC
Below is the current result set based on the query above.
Your code looks really strange. I would expect the query to use conditional aggregation and look more like this:
SELECT ORDERS.StorerKey, ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'C' THEN BAX_PACK_DTL.OuterPackID END),
TotalPallet = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'P' THEN BAX_PACK_DTL.OuterPackID END),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'C' AND pbd.PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'P' AND pbd.PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM . . .
GROUP BY ORDERS.StorerKey, ORDERS.OrderKey, Upper(ORDERS.ExternOrderKey),
Upper(ORDERS.EditWho), ORDERS.AddDate;
This may not be exact. You have not qualified column names, given the table structure, and are using very arcane query syntax, mixing subqueries and aggregations. But it should give an idea.

SQL XML dd/mm/yyyy failing to return as string

I am working with a legacy system that only accepts dd/mm/yyyy in the XML for the data fields otherwise it mucks up the data entry.
I have tried every which way to attempt to force my data fields to display as dd/mm/yyyy, I have attempted to CONVERT to DATETIME 103, I have tried declaring it as a VARCHAR and everytime time it returns as 2018-05-11 for example.
How can I force the returned field to display as DD/MM/YYYY, this is a snippet of my code, excuse how messy it is unfortunately it is very linear and the system that accepts the XML is very basic.
SELECT TOP 1 1 'job/queue',
#Branch 'job/branch',
CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END 'parameters/yzt/char20.1',
SUBSTRING(#PolicyRef,1,6) 'broomsdata/broomsclient/bcm/refno',
#PolicyRef 'broomsdata/broomspolicy/bpy/refno',
CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END 'broomsdata/broomspolicy/myli/KEY',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Date1',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Code1',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Fine1',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Points1',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Date2',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Code2',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Fine2',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Points2',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Date3',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Code3',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Fine3',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Points3',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Date4',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Code4',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Fine4',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Points4'
FROM #ConvictionTable AS ct
LEFT OUTER JOIN [FIG-SQL-SRV].InfoCentre.dbo.ic_BD_MYLI AS myli ON ct.branch = myli.B# AND ct.policyRef = myli.PolRef#
FOR XML PATH('xmlexecute'), TYPE;
The Fields I'm trying to force are the 'Date1'/'Date2' etc. fields.
Cheers
Use CONVERT(varchar(10), YourDateColumn, 103). I think your mistake was trying to convert to a datetime (I'm guessing you tried CONVERT(datetime, YourDateColumn, 103)) while using a style code; date/time datatypes, in SQL Server, have no format. Trying to format them won't do anything.
For example: SELECT CONVERT(varchar(10), GETDATE(), 103); returns the varchar(10) value '11/05/2018'.
Edit: The below is to (temporary) assist the OP in showing how i create XML for OpenInterchange. The OP is using a lot of Sub Selects, something that doesn't help the speed of the query. I've highlighted, a couple of points for the OP to note as well:
SELECT K.Insco AS Insurer,
K.B# AS Branch,
K.PolRef# AS PolicyRef,
K.ClaimRef# AS ClaimRef,
--XML Generation starts here.
(SELECT(SELECT K.B# AS branch,
'OO' AS operator,
'PDF' AS printtype
FOR XML PATH('job'),TYPE),
(SELECT (SELECT 'update-claim' AS [Char20.1]
FOR XML PATH('yzt'),TYPE)
FOR XML PATH('parameters'),TYPE),
(SELECT (SELECT (SELECT K.Ref# AS Refno
FOR XML PATH('bcm'),TYPE)
FOR XML PATH('broomsclient'),TYPE),
(SELECT (SELECT K.PolRef# AS Refno
FOR XML PATH('bpy'),TYPE)
FOR XML PATH('broomspolicy'),TYPE),
(SELECT (SELECT K.ClaimRef# AS [Claim.No],
K.[Claim No] AS [Ins.Claim.Ref],
K.KGMSettled AS [Claim.Settled],
K.KGMReserve AS [Claim.Reserve],
K.KGMReserve + K.KGMSettled As [Claim.Amount],
K.KGMStatus AS [Stat.Desc],
CASE K.KGMStatus WHEN 'Settled' THEN 'SETT'
WHEN 'Ouststanding' THEN 'OUTS'
WHEN 'Declined' THEN 'DECL'
WHEN 'Not Taken up' THEN 'NTUP'
WHEN 'Withdrawn' THEN 'WITH' END AS [stat.code],
CONVERT(varchar(10),K.[Notified Date],103) AS [Date.repd], --First example of the dd/MM/yyyy format
CONVERT(varchar(10),K.[Loss Date],103) AS [Loss.date], --Another example of the dd/MM/yyyy format
CASE WHEN K.[Date Closed] IS NOT NULL THEN CONVERT(varchar(10), GETDATE(), 103) END AS [Stat.date], -- and another example of the dd/MM/yyyy format
CONVERT(varchar(10),K.[Date Closed],103) AS [Date.Settled], --you get the idea. :)
CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.[Date Closed] IS NULL THEN ''
WHEN K.[NCB Decision] = 'Allowed' THEN 'Yes'
WHEN K.[NCB Decision] = 'Disallowed' THEN 'Yes' END AS [Settled.free]
/*
CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.KGMReserve + K.KGMSettled = 0 AND K.[Date Closed] IS NOT NULL THEN 'Yes'
WHEN K.KGMReserve + K.KGMSettled > 0 AND K.[Date Closed] IS NOT NULL THEN 'No'
ELSE '' END AS [Settled.free]*/
FOR XML PATH('bch'),TYPE),
(SELECT K.BCAKey AS [KEY],
K.[Vehicle Reg# No] AS [Reg.no],
K.[Driver Name] AS [Driver],
K.[ AD Paid] AS [Pay.ad],
K.[AD Reserve] AS [Reserve.ad],
K.[TPD Paid] + K.[TPI Paid] AS [Pay.tp],
K.[TPD Reserve] + K.[TPI Reserve] AS [Reserve.tp],
--K.[TPI Paid] AS [Pay.others],
--K.[TPI Reserve] AS [Reserve.others],
0 AS [Pay.others],
0 AS [Reserve.others],
K.KGMSettled AS [Pay.total],
K.KGMReserve AS [Reserve.Total],
K.[Recovery] AS [Pay.recovs],
K.[AD Recovery Reserve] AS [Reserve.recovs],
'Updated by FileDrop Service. XML Generated on ' + CONVERT(varchar(10),GETDATE(),103) as [Remarks4]
FOR XML PATH('bca'),TYPE),
(SELECT CONVERT(varchar(10),GETDATE(),103) AS [date],
LEFT(CONVERT(varchar(10),GETDATE(),108),5) AS [time],
'OO' AS [op],
'FileDrop' AS [Name],
K.KGMSettled AS [Settled],
K.KGMReserve AS [Reserve],
K.KGMSettled + K.KGMReserve As [Total],
--CONVERT(varchar(10),K.DataToDate,103) AS [EffDate],
CASE WHEN K.KGMSettled != K.BCHSettled THEN 'Payment'
WHEN K.KGMReserve != K.BCHReserve THEN 'Reserve Adjustment'
ELSE 'Payment' END AS [Notes]
FOR XML PATH('clam'),TYPE)
FOR XML PATH('broomsclaim'),TYPE)
FOR XML PATH('broomsdata'),TYPE)
FOR XML PATH('xmlexecute'),TYPE) AS InputXML,
GETDATE() AS DateGenerated,
0 AS TestLoad
FROM KGMCGStandard_viw K
WHERE K.ClaimsFound = 1
AND K.KGMFound = 1
AND (K.KGMSettled != K.BCHSettled
OR K.KGMReserve != K.BCHReserve
OR (CONVERT(date,K.KGMClosure) != CONVERT(date,BCHClosure)
OR (K.KGMClosure IS NULL AND K.BCHClosure IS NOT NULL)
OR (K.KGMClosure IS NOT NULL AND K.BCHClosure IS NULL))
OR (CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.[NCB Decision] = 'Allowed' THEN 'Yes'
WHEN K.[NCB Decision] = 'Disallowed' THEN 'No' END != K.Settled_Free
OR (K.[Date Closed] IS NULL AND K.Settled_free IS NULL)))
AND NOT EXISTS (SELECT 1
FROM AutoloadXML_tbl A
WHERE A.Branch = K.B#
AND A.PolicyRef = K.PolRef#
AND A.ClaimRef = K.ClaimRef#
AND (A.DateSubmitted IS NULL
OR A.Installed = 0))
ORDER BY K.ClaimRef# ASC;
Since you already figured out the date part I will leave that up to you but your query could be simplified majorly using conditional aggregation. I used square braces around the column names instead of single quotes. Sure those work but I consider that a bad habit because it is difficult to decide if it is a string literal or a column alias. I also prefer to use alias = but that is more a preference thing. I also prefer leading commas which is also a preference thing.
Pretty sure this query should do the same thing.
SELECT 1 as 'job/queue',
#Branch as 'job/branch',
CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END as 'parameters/yzt/char20.1',
SUBSTRING(#PolicyRef,1,6) as 'broomsdata/broomsclient/bcm/refno',
#PolicyRef as 'broomsdata/broomspolicy/bpy/refno',
CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END as 'broomsdata/broomspolicy/myli/KEY'
, [broomsdata/broomspolicy/myli/Date1] = max(case when ct.RowNo = 1 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code1] = max(case when ct.RowNo = 1 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine1] = max(case when ct.RowNo = 1 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points1] = max(case when ct.RowNo = 1 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date2] = max(case when ct.RowNo = 2 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code2] = max(case when ct.RowNo = 2 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine2] = max(case when ct.RowNo = 2 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points] = max(case when ct.RowNo = 2 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date3] = max(case when ct.RowNo = 3 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code3] = max(case when ct.RowNo = 3 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine3] = max(case when ct.RowNo = 3 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points3] = max(case when ct.RowNo = 3 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date4] = max(case when ct.RowNo = 4 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code4] = max(case when ct.RowNo = 4 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine4] = max(case when ct.RowNo = 4 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points4] = max(case when ct.RowNo = 4 then ct.noofpoints end)
FROM #ConvictionTable AS ct
LEFT OUTER JOIN [FIG-SQL-SRV].InfoCentre.dbo.ic_BD_MYLI AS myli ON ct.branch = myli.B# AND ct.policyRef = myli.PolRef#
GROUP BY #Branch
, CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END
, SUBSTRING(#PolicyRef,1,6)
, #PolicyRef
, CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END
FOR XML PATH('xmlexecute'), TYPE

incorrect syntax in over and partition by with temporary tables

I have a partition-by function in my stored procedure which calls for a temporary table from a previous partition-by function. The table that I created with the previous partition by function is #tempVehicleManifestRow which in turn is what I call for the next partition by function. What happens is that it shoes the error
"incorrect syntax near ' #tempVehicleManifestRow'"
Why is this happening? Isn't it that I have already generated a temporary table with the data needed even before I actually selected it?
I have attached below the partition by functions I used.
This is my first partition by function:
;WITH A AS
(
SELECT ROW_NUMBER() OVER(ORDER BY
CASE
when #pOrderby = 'SortByGender' then T.Gender
when #pOrderby = 'SortByCost' then T.colCostCenterCodeVarchar
when #pOrderby = 'SortByPickupDate' then cast(T.colPickUpDate as varchar(20))
when #pOrderby = 'SortByLastName' then T.LastName
when #pOrderby = 'SortByFirstName' then T.FirstName
when #pOrderby = 'SortByEmployeeID' then cast(T.colSeafarerIdInt as varchar(20))
when #pOrderby = 'SortByShip' then T.VesselName
when #pOrderby = 'SortByTitle' then T.RankName
when #pOrderby = 'SortByRouteFrom' then T.RouteFrom
when #pOrderby = 'SortByRouteTo' then T.RouteTo
when #pOrderby = 'SortByFromCity' then T.colFromVarchar
when #pOrderby = 'SortByToCity' then T.colToVarchar
when #pOrderby = 'SortByVehicleTypeName' then T.VehicleTypeName
when #pOrderby = 'SortByStatus' then T.VehicleTypeName
when #pOrderby = 'SortByCostCenter' then T.colCostCenterCodeVarchar
when #pOrderby = 'SortByNationality' then T.Nationality
when #pOrderby = 'SortByVehicleVendor' then T.VehicleVendorname
when #pOrderby = 'SortByRecordLocator' then T.colRecordLocatorVarchar
when #pOrderby = 'SortByOnOffdate' then cast(T.colOnOffDate as varchar(20))
when #pOrderby = 'SortByPickupTime' then cast(T.colPickUpTime as varchar(20))
when #pOrderby = 'SortByOnOff' then T.colSFStatus
when #pOrderby = 'SortByHotel' then T.HotelVendorName
ELSE
T. VehicleVendorname
END ,
CASE WHEN #pOrderby = 'SortByPickupDate' then cast(T.colPickUpTime as varchar(20))
ELSE T.FirstName
END
) AS xRow,
* FROM #tempVehicleManifest T
) SELECT * INTO #tempVehicleManifestRow FROM A ORDER BY A.xRow
This is the partition-by that is are having problems:
;WITH CC AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY CC.colRecordLocatorVarchar, CC.colSeafarerIdInt,
CC.colOnOffVarchar , CC.colVehicleVendorIDInt
ORDER BY CC.colTagIDInt DESC) xRow, CC.*
FROM (
SELECT distinct
A.xRow,
A.colTransVehicleIDBigint,
A.colSeafarerIdInt, A.LastName, A.FirstName,
A.colIdBigint, A.colTravelReqIDInt,
A.colRecordLocatorVarchar, A.colOnOffDate,
A.colRequestIDInt, A.colVehicleVendorIDInt,
A.VehicleVendorname, A.colVehiclePlateNoVarchar,
A.colPickUpDate, A.colPickUpTime,
A.colDropOffDate, A.colDropOffTime,
A.colConfirmationNoVarchar, A.colVehicleStatusVarchar,
A.colVehicleTypeIdInt, A.VehicleTypeName, A.colSFStatus,
A.colRouteIDFromInt, A.RouteFrom, A.colRouteIDToInt, A.RouteTo,
A.colFromVarchar, A.colToVarchar, A.colRemarksForAuditVarchar,
A.colHotelIDInt, A.HotelVendorName, A.colRankIDInt, A.RankName,
A.colCostCenterIDInt, A.colCostCenterCodeVarchar,
Nationality = RTRIM(LTRIM(N.colNationalityCodeVarchar)) + '-' + RTRIM(LTRIM(N.colNationalityDescriptionVarchar)),
A.colIsVisibleBit,
A.colContractIdInt, A.Gender, A.colVesselIdInt,
A.VesselName, UserID = #pUserID, A.colSeqNoInt
, A.colDriverIDInt
--, A.colIsNoVehicleNeeded
, A.colVehicleDispatchTime
, FlightNo =A.colFlightNoVarchar
, Carrier = A.colMarketingAirlineCodeVarchar
, Departure = A.colDepartureAirportLocationCodeVarchar
, Arrival = A.colArrivalAirportLocationCodeVarchar
, DeptDate = A.colDepartureDateTime
, ArrDate = A.colArrivalDateTime
, PA.PassportNo
, PA.PassportExp
, PA.PassportIssued
, BR.Birthday
, ISNULL(CC.colIsActiveBit,0) as colIsActiveBitTagged
, CC.colCreatedByVarchar as createdUserTag
, CC.colModifiedByVarchar as modifiedUserTag
, CC.colVehicleVendorIDInt as taggedVehicleVendorId
#tempVehicleManifestRow A
LEFT JOIN TblVehicleManifestConfirmed B ON
A.colSeafarerIdInt = B.colSeafarerIdInt AND
A.colVehicleVendorIDInt = B.colVehicleVendorIDInt AND
A.colPickUpDate = B.colPickUpDate AND
ISNULL(A.colRecordLocatorVarchar,'') = ISNULL(B.colRecordLocatorVarchar,'')
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--not visible to vendor but not realy cancelled
LEFT JOIN TblVehicleManifestConfirmed Hide ON
A.colSeafarerIdInt = Hide.colSeafarerIdInt AND
A.colVehicleVendorIDInt = Hide.colVehicleVendorIDInt AND
A.colPickUpDate = Hide.colPickUpDate AND
ISNULL(A.colRecordLocatorVarchar,'') = ISNULL(Hide.colRecordLocatorVarchar,'') AND
ISNULL(Hide.colIsVisibleBit,1) = 0
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--added new table
LEFT JOIN TblTag_Vehicle CC ON B.colIdBigint = CC.colIdBigint AND
B.colTravelReqIDInt = CC.colTravelReqIDInt AND B.colSeafarerIdInt = CC.colSeafarerIdInt
--end new added table
LEFT JOIN dbo.TblVehiclePlates VP ON VP.colPlateID = B.colVehiclePlateNoVarchar
LEFT JOIN dbo.TblSeafarer S ON S.colSeafarerIdInt = A.colSeafarerIdInt
LEFT JOIN TblNationality N ON N.colNatioalityIdInt = S.colNationalityIDInt
LEFT JOIN #TempPassport PA ON A.colSeafarerIdInt = PA.SeafarerId
LEFT JOIN tmRemarks_Birthday BR ON BR.FK_ItineraryRefID = A.colRecordLocatorVarchar
JOIN #tempVehicleVendor VE ON VE.colVehicleVendorIDInt = A.colVehicleVendorIDInt
WHERE
( B.colConfirmedManifestIDBigint IS NULL
OR
Hide.colTransVehicleIDBigint IS NOT NULL
)
ORDER BY A.xRow
)
) SELECT * INTO #tempManifestNew
You have missed the FROM CLAUSE in this query near #tempVehicleManifestRow A. Here is the correct query.
;WITH CC
AS (
SELECT ROW_NUMBER() OVER (
PARTITION BY CC.colRecordLocatorVarchar
,CC.colSeafarerIdInt
,CC.colOnOffVarchar
,CC.colVehicleVendorIDInt ORDER BY CC.colTagIDInt DESC
) xRow
,CC.*
FROM (
SELECT DISTINCT A.xRow
,A.colTransVehicleIDBigint
,A.colSeafarerIdInt
,A.LastName
,A.FirstName
,A.colIdBigint
,A.colTravelReqIDInt
,A.colRecordLocatorVarchar
,A.colOnOffDate
,A.colRequestIDInt
,A.colVehicleVendorIDInt
,A.VehicleVendorname
,A.colVehiclePlateNoVarchar
,A.colPickUpDate
,A.colPickUpTime
,A.colDropOffDate
,A.colDropOffTime
,A.colConfirmationNoVarchar
,A.colVehicleStatusVarchar
,A.colVehicleTypeIdInt
,A.VehicleTypeName
,A.colSFStatus
,A.colRouteIDFromInt
,A.RouteFrom
,A.colRouteIDToInt
,A.RouteTo
,A.colFromVarchar
,A.colToVarchar
,A.colRemarksForAuditVarchar
,A.colHotelIDInt
,A.HotelVendorName
,A.colRankIDInt
,A.RankName
,A.colCostCenterIDInt
,A.colCostCenterCodeVarchar
,Nationality = RTRIM(LTRIM(N.colNationalityCodeVarchar)) + '-' + RTRIM(LTRIM(N.colNationalityDescriptionVarchar))
,A.colIsVisibleBit
,A.colContractIdInt
,A.Gender
,A.colVesselIdInt
,A.VesselName
,UserID = #pUserID
,A.colSeqNoInt
,A.colDriverIDInt
--, A.colIsNoVehicleNeeded
,A.colVehicleDispatchTime
,FlightNo = A.colFlightNoVarchar
,Carrier = A.colMarketingAirlineCodeVarchar
,Departure = A.colDepartureAirportLocationCodeVarchar
,Arrival = A.colArrivalAirportLocationCodeVarchar
,DeptDate = A.colDepartureDateTime
,ArrDate = A.colArrivalDateTime
,PA.PassportNo
,PA.PassportExp
,PA.PassportIssued
,BR.Birthday
,ISNULL(CC.colIsActiveBit, 0) AS colIsActiveBitTagged
,CC.colCreatedByVarchar AS createdUserTag
,CC.colModifiedByVarchar AS modifiedUserTag
,CC.colVehicleVendorIDInt AS taggedVehicleVendorId
-- HERE YOU HAVE MISSED FROM CLAUSE
FROM #tempVehicleManifestRow A
LEFT JOIN TblVehicleManifestConfirmed B ON A.colSeafarerIdInt = B.colSeafarerIdInt
AND A.colVehicleVendorIDInt = B.colVehicleVendorIDInt
AND A.colPickUpDate = B.colPickUpDate
AND ISNULL(A.colRecordLocatorVarchar, '') = ISNULL(B.colRecordLocatorVarchar, '')
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--not visible to vendor but not realy cancelled
LEFT JOIN TblVehicleManifestConfirmed Hide ON A.colSeafarerIdInt = Hide.colSeafarerIdInt
AND A.colVehicleVendorIDInt = Hide.colVehicleVendorIDInt
AND A.colPickUpDate = Hide.colPickUpDate
AND ISNULL(A.colRecordLocatorVarchar, '') = ISNULL(Hide.colRecordLocatorVarchar, '')
AND ISNULL(Hide.colIsVisibleBit, 1) = 0
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--added new table
LEFT JOIN TblTag_Vehicle CC ON B.colIdBigint = CC.colIdBigint
AND B.colTravelReqIDInt = CC.colTravelReqIDInt
AND B.colSeafarerIdInt = CC.colSeafarerIdInt
--end new added table
LEFT JOIN dbo.TblVehiclePlates VP ON VP.colPlateID = B.colVehiclePlateNoVarchar
LEFT JOIN dbo.TblSeafarer S ON S.colSeafarerIdInt = A.colSeafarerIdInt
LEFT JOIN TblNationality N ON N.colNatioalityIdInt = S.colNationalityIDInt
LEFT JOIN #TempPassport PA ON A.colSeafarerIdInt = PA.SeafarerId
LEFT JOIN tmRemarks_Birthday BR ON BR.FK_ItineraryRefID = A.colRecordLocatorVarchar
JOIN #tempVehicleVendor VE ON VE.colVehicleVendorIDInt = A.colVehicleVendorIDInt
WHERE (
B.colConfirmedManifestIDBigint IS NULL
OR Hide.colTransVehicleIDBigint IS NOT NULL
)
) AS x -- missing alias declaration, required in TSQL
)
SELECT *
INTO #tempManifestNew

Create Clustered/Non Clustered Index in view

I am having a view which returns value to a table. The process takes a long time... So I felt it works better if go for indexing on view. Can anyone plz guide me to add index to view.
ALTER View [dbo].[GetApplicationBudgetAndUtilized]
as
Select *, (convert(money,isnull(TotalBudget,0)) - convert(money,isnull(Utilized,0))) as [Left] from (
SELECT Distinct PM.PKID AS ProgramID, F.PKID as FundID, I.PKID as ProjectID,
MYB.PKID AS MultiYearBudgetID,
(Select Isnull(Sum(IsNull(PBC1.BudgetAmount,0)),0) from ProgramBudgetConfiguration PBC1
Where pbc1.MultiYearBgtIdFkId = pbc.MultiYearBgtIdFkId and PBC1.IsActive = 1 and LOVBudgetTypeIDFKID = 'BT_INC' group
by pbc1.MultiYearBgtIdFkId) AS TotalProgramBudget,
App.TotalBudget,
I.PKID,
(Case when exists (Select 'x' from InstallationTransactionHeader Where ParentPrjNumber = I.PKID and IsDelete = 0)
then
(case
when not exists (select cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)
from InstallationTransactionHeader I1 where I1.ParentPrjNumber is not null and I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and
I1.ParentPrjNumber = I.PKID and I1.FundRequestIDFKID is not null) then (select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and I1.ParentPrjNumber is not null and
I1.ParentPrjNumber = I.PKID and I1.isdelete = 0 and I1.FundRequestIDFKID is not null group by I1.parentPrjNumber)
End)
else
--isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0)
(case
when not exists (select isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0) from
InstallationTransactionHeader I where StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and
PKID = I.PKID and I.FundRequestIDFKID is not null) then 0--(select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and I1.FundRequestIDFKID is not null and
PKID = I.PKID)
End)
End) as Utilized
--Cast(App.TotalBudget - (isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00)) as Money) as [Left]
FROM
( SELECT PKID as FundID, ProgramID AS ProgramID, (ISNULL(IncentiveAmount,0.00) + ISNULL(CustInstallIncAmt, 0.00) + ISNULL(SPInstIncentiveAmt, 0.00) ) AS TotalBudget
FROM dbo.FundRequestHeader AS F WHERE (IsDelete = 0) AND (IsActive = 1) AND (StatusFKID in ('IAS_APP','IAS_CAN'))) AS App
INNER JOIN dbo.ProgramMaster AS PM
INNER JOIN dbo.MultiYearBudget AS MYB ON PM.PKID = MYB.ProgramIDFKID
INNER JOIN dbo.ProgramBudgetConfiguration AS PBC ON MYB.PKID = PBC.MultiYearBgtIdFkId ON App.ProgramID = PM.PKID
INNER JOIN dbo.FundRequestHeader AS F ON F.PKID = App.FundID
INNER JOIN dbo.InstallationTransactionHeader AS I ON I.FundRequestIDFKID = F.PKID
WHERE (PM.IsActive = 1) AND (MYB.IsActive = 1) AND (PBC.IsActive = 1) AND
(PBC.LOVBudgetTypeIDFKID = 'BT_INC') And (F.StatusFKID in ('IAS_APP','IAS_CAN'))
--and (1=case when(select ProgramTypeIDFKID from InstallationTransactionHEader where ProgramTypeIDFKID='IT_PRE' and ParentPrjNumber is null and PaymentSchedule=1)='IT_PRE' then 0 else 1 end)
--and I.ProgramTypeIDFKID <> 'IT_PRE' or I.PaymentSchedule = 0 or (I.ProgramTypeIDFKID = 'IT_PRE' and I.PaymentSchedule = 1 and I.ParentPrjNumber is not null)
and MYB.PKID = F.BudgetPeriodID and ((MYB.IsActive = 1))-- or ((MYB.status = 0) and F.StatusFKID ='IAS_APP'))
and (MYB.Status = 1 or (MYB.Status =(case when exists(select M.status from MultiYearBudget M, FundRequestHeader F
where F.ProgramID=M.ProgramIDFKID and F.ProgramTypeIDFKID <>'IT_FCFS' and M.Pkid=F.BudgetPeriodID
and F.StatusFKID='IAS_APP' and F.ProgramID=PM.PKID and M.Status=0 )then 0 else 1 end))
)
)temp
GO
Indexed views have certain limitations
In your case, I can immediately see some blockers
SELECT *
Derived tables
So read this article, and see how far you get...
However, you should be able to look the execution plan identify bottlenecks where you can add indexes to the bases tables