How to fix error 102 on SQL Server - sql

i have problems in sql please help me
sql query :
SELECT CASE
WHEN (GROUPING(Staff.FirstName + ' ' + Staff.LastName ) = 1) THEN 'ALL'
ELSE ISNULL(Staff.FirstName + ' ' + Staff.LastName , 'UNKNOWN') END AS Staff.FirstName + ' ' + Staff.LastName , Count( Patient.PatientUniqueID ) AS CountOfPatientID
FROM patient LEFT JOIN
((bInsurance RIGHT JOIN
((Admit LEFT JOIN Staff ON Admit.DoctorRef = Staff.GeneralID) LEFT JOIN bWard ON Admit.WardRef = bWard.WardID)
ON bInsurance.InsurID = Admit.InsuranceRef)
LEFT JOIN (Staff AS Staff_Treat RIGHT JOIN PTreat ON Staff_Treat.GeneralID = PTreat.DoctorRef)
ON Admit.AdmitID = PTreat.AdmitRef) ON patient.PatientUniqueID = Admit.PatientUniqueRef
Where (PatientUniqueID IN(
SELECT Patient.PatientUniqueID
FROM Staff AS StaffUserInf RIGHT JOIN
((((bWard RIGHT JOIN (Staff RIGHT JOIN Admit ON Staff.StaffID=Admit.DoctorRef) ON bWard.WardID=Admit.WardRef)
LEFT JOIN Staff AS Staff_1 ON Admit.AssistantRef=Staff_1.StaffID)
RIGHT JOIN Patient ON Admit.PatientUniqueRef=Patient.PatientUniqueID)
LEFT JOIN PTreat ON Admit.AdmitID=PTreat.AdmitRef)
ON StaffUserInf.UserName=Admit.CreatedBy Where 1 = 1 ) )
GROUP BY Staff.FirstName + ' ' + Staff.LastName ;With Cube
error :
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 17
Incorrect syntax near ')'.

Related

Syntax error in Common Table Expression 1

I am trying to create a common table expression but I got an error.
Could you please help me with that.
WITH cte_sales AS(
SELECT
Payments.BankTransaction_Id,
Payments.Paid * InvoiceLines.TotalPrice / Invoices.TotalPayable AS PaymentAmount,
FORMAT( Cast(Payments.Paid / Invoices.TotalPayable as Decimal(6,1)) ,'P0') AS PaymentAmount,
Invoices.TotalPayable,
Payments.PaymentDate,
BankTransactions.TransactionDate,
ProductContracts.Product_Id,
ProductBases.Name AS ProductName,
ProductOptionBases.Name As ProductOptionName,
InvoiceLines.InvoiceLineId,
CubeOrder.Id AS ContractId,
ProductContracts.RowID AS ProductContractId
FROM Payments
INNER JOIN Invoices ON Invoices.Id = Payments.Invoice_Id
INNER JOIN InvoiceLines ON InvoiceLines.Invoice_Id = Invoices.Id
INNER JOIN ProductContracts ON CAST(ProductContracts.ContractID AS VARCHAR(100)) = SUBSTRING(InvoiceLines.InvoiceLineId, 1, 36)
INNER JOIN ProductOptionBases ON CAST(ProductOptionBases.Id AS VARCHAR(5)) = SUBSTRING(InvoiceLines.InvoiceLineId, 38, IIF (CHARINDEX(':', InvoiceLines.InvoiceLineId, 38) = 0, 999, CHARINDEX(':', InvoiceLines.InvoiceLineId, 38))- 38)
INNER JOIN ProductBases ON ProductContracts.Product_Id = ProductBases.Id
INNER JOIN CubeOrder ON CubeOrder.ContractID = Invoices.SubjectID
INNER JOIN BankTransactions ON BankTransactions.Id = Payments.BankTransaction_Id
WHERE ProductContracts.Discriminator = 'RecurringProductContract'
AND Invoices.TotalPayable <> 0
)
The error message is: Msg 102, Level 15, State 1, Line 26 Incorrect syntax near ')'.
You are missing the main query, that you need to add at the end.
For example, a query with a CTE should take the form:
with cte_sales as (
...
)
select * from cte_sales
You are missing that last line.

Invalid Column in SQL SubQuery

I am trying to run a query below and I am getting the following errors and unable to figure out.
Please look at how column AllocPer is being calculated. That's where the errors are coming from:
Msg 207, Level 16, State 1, Procedure USP_RS_Dealio_JLL_ECRDetails_test, Line 688
Invalid column name 'dealid'.
Msg 207, Level 16, State 1, Procedure USP_RS_Dealio_JLL_ECRDetails_test, Line 689
Invalid column name 'empid'.
My SQL code:
SELECT
MarketPerDiff, CommissionDate, empid, dealid
INTO
#vwDealEmpSplitDetail_Emp
FROM
dbo.vwDealEmpSplitDetail_Emp
PRINT 'Query 1 Starts at ' + CONVERT(nvarchaR(36), getdate(), 114)
SET# t1 = GETDATE()
SELECT
Per.enddate "CommEndDate",
'Period ' + CAST(Per.Period AS VARCHAR) "SubPeriod",
Col.EligibleDate AS "CollectionDate",
Col.DealID,
Client.clientName,
Deal.DealName,
Col.EmpID AS "ProfID",
Emp.FullName AS "ProfName",
SUM(ISNULL(Col.CashCollected, 0)) CashCollected,
Stat.MarketID,
Stat.OpUnit,
HB.Description,
SUM(ISNULL(Col.CostHurdle, 0)) AS "DEmpCostHurdle",
ISNULL(Prof.DealCostMultiplier, 50)[DealCostMultiplier],
(SELECT SUM(MarketPerDiff) "MarketPerDiff"
FROM #vwDealEmpSplitDetail_Emp
WHERE #vwDealEmpSplitDetail_Emp.dealid = Deal.DealID AND
#vwDealEmpSplitDetail_Emp.empid = Emp.EmpID) as AllocPer
INTO
#SummedValues
FROM
tblEmpCollectionAdj Col WITH(NOLOCK)
JOIN
tblDeal Deal WITH(NOLOCK) ON Deal.DealID = Col.DealID
LEFT JOIN
dbo.tblClient Client WITH(NOLOCK) ON Client.ClientCode = Deal.ClientCode
JOIN
tblMktOpUnitCompStatus Stat WITH(NOLOCK) ON Stat.BatchID = Col.BatchID
LEFT JOIN
dbo.tblEmployee Emp WITH(NOLOCK) ON Emp.EmpID = Col.EmpID AND Emp.Active = 1
LEFT JOIN
dbo.tblCommPeriod Per WITH(NOLOCK) ON Col.EligibleDate BETWEEN Per.StartDate AND Per.Enddate
LEFT JOIN
tblEmpCompProfile Prof WITH(NOLOCK) ON Prof.EmpID = Col.EmpId
AND Prof.Active = 1
AND Prof.PeriodID = #PeriodId
AND Prof.Batchid = Col.Batchid
LEFT JOIN
tblHBAlloc HB ON HB.HBAcctEmpID = Prof.EmpID
AND HB.OpUnit = Prof.OpUnit
AND HB.CF3 = Prof.MarketId
AND HB.FiscalYear = #Year1
WHERE
Col.Active = 1
AND Deal.Active = 1
AND Col.PeriodId = #PeriodId
AND ISNULL(Col.CashCollected, 0) + ISNULL(Col.CostHurdle, 0) NOT BETWEEN - .01 AND.01
GROUP BY
Per.enddate,
'Period ' + CAST(Per.Period AS VARCHAR),
Col.EligibleDate, Col.DealID, Client.clientName,
Deal.DealName,
Col.EmpID,
Emp.FullName,
Col.CashCollected,
Stat.MarketID, Stat.OpUnit,
HB.Description,
ISNULL(Prof.DealCostMultiplier, 50),
deal.dealid, Emp.empid, Per.StartDate, Per.Enddate
PRINT 'Query 1 Ends ' + CONVERT(nvarchaR(36), getdate(), 114)
SET# t2 = GETDATE()
PRINT ' TIME ELAPSED ' + CAST(DATEDIFF(millisecond, #t1, #t2) AS NVARCHAR(255))
The error should be self-explanitory. It seems that you are referencing a column that does not exist in a table you are trying to access it from. Without access to your table structure, unfortunately we can only guess at the issue. However, your error says that the columns dealid and empid are invalid. I see that they are being used in several places.
Check to ensure that dealid exists in the following tables/views: tblEmpCollectionAdj, vwDealEmpSplitDetail_Emp, tblDeal.
And check that empid exists in the following tables/views: vwDealEmpSplitDetail_Emp, tblEmpCollectionAdj, tblEmployee, tblEmpCompProfile.
Also, a point that #Blorgbeard mentioned in a comment, check that you are using the proper casing for the column and for table aliases. You have the table tblDeal aliased as Deal, however you reference it as deal in at least one place.

How to solve The multi-part identifier "r.StandardRate" could not be bound

I am getting the following error for the query shown below:
Msg 4104, Level 16, State 1, Line 37
The multi-part identifier "r.ResourceId" could not be bound.
Msg 4104, Level 16, State 1, Line 16
The multi-part identifier "r.StandardRate" could not be bound.
Can you please help me figure this out?
Query:
select
vnd.Name as VendorName,
cct.Name as CostCentreName,
ct.Name as CostType,
case when cct.IsActive = 1 then 'ACTIVE' else 'CLOSED' end as CCStatus,
isnull(cct.T1Code,'') as T1Code,
cct.T2Code,
'' as [Month],
convert(varchar, year(pf.period)) + '-' + convert(varchar, month(pf.period)) as Period,
pp.ParentProformaNo,
pf.ProformaNo,
vac.TrafiguraAccountCode,
vac.PumaAccountCode,
pli.FinalAmt as Ammount,
ts.Quantity as Quantity,
r.StandardRate as StandardRate,
cmp.[Text] as ProformaStatus,
'' as BillableUOM,
'' as Currency,
bet.Entity as CCBilledEntity,
bcet.Name as CCBilledCompany,
pbet.Entity as ProformaBilledEntity,
pbcet.Name as ProformaBilledCompany
from
ProformaParent pp
join
Proforma pf on pf.ProformaParentId = pp.Id
join
ProformaCostCentre pcc on pcc.ProformaId = pf.ProformaId
join
CostCentre cct on cct.Id = pcc.CostCentreId
join
ProformaLineItems pli on pli.ProformaId = pcc.ProformaId
and pli.ProformaCostCentreId = pcc.ProformaCostCentreId
join
Vendor vnd on vnd.Id = pf.VendorId
join
CostType ct on ct.Id = pli.CostTypeId
join
VendorAccountCode vac on vac.VendorMId = vnd.Id
and vac.CostTypeMId = ct.Id
join
CodeMaster cmp on cmp.Id = pf.StatusId
join
BilledEntity bet on bet.Id = cct.BilledEntityMId
join
Entity bcet on bcet.Id = cct.BilledCompanyEntityId
join
BilledEntity pbet on pbet.Id = pf.BilledEntityId
join
Entity pbcet on pbcet.Id = pf.BilledCompanyId
join
TimeSheet ts on ts.ResourceId = r.ResourceId
There is simply no object in your query named r.

SQL Server : 'Could not be bound' - Error

I have a dynamic stored procedure, it's long so I'll just provide the part that is causing the error.
SELECT #sSql = #sSql + '
animal.AnimalId,
species.Code AS Species,
breed.Code AS Breed ,
country.CountryId AS CountryId ,
country.Code AS CountryCode ,
animal.Sex AS Sex ,
animalRegistration.Identifier AS RegNo ,
breed.Description + country.Code + animal.Sex + animalRegistration.Identifier AS FullRegNo,
thePrefix.Prefix AS Prefix,
animal.Name AS Name,
thePrefix.Prefix + animal.Name AS FullName,
animal.Name AS EarTag1,
animal.DateOfBirth as DateOfBirth ,
0 as AnimalFlagCount'
--isnull( Genomics.GetAnimalFlagCount( a.AnimalId,' + CAST(#IsCatalogSamples AS VARCHAR(2)) + ' ), 0) AS AnimalFlagCount '
--a.EarTag1
SELECT #sFrom = '
FROM dbo.Animal AS animal
LEFT JOIN dbo.Breed breed ON animal.BreedId = breed.BreedId
LEFT JOIN dbo.Species species ON species.SpeciesId = breed.SpeciesId
LEFT JOIN dbo.AnimalIdentity animalIdentity ON animalIdentity.AnimalId = animal.AnimalId
LEFT JOIN dbo.AnimalIdentity animalRegistration ON animalRegistration.AnimalId = animal.AnimalId and animalRegistration.IdentityTypeId = 2
LEFT JOIN dbo.Country country ON animalIdentity.CountryId = country.CountryId
LEFT JOIN dbo.AnimalPrefix animalPrefix ON animalPrefix.AnimalId = animal.AnimalId
LEFT JOIN dbo.Prefix thePrefix ON thePrefix.PrefixId = animalPrefix.PrefixId
WHERE
'
This is returning the error:
Msg 4104, Level 16, State 1, Line 10
The multi-part identifier "thePrefix.Prefix" could not be bound.
Msg 4104, Level 16, State 1, Line 12
The multi-part identifier "thePrefix.Prefix" could not be bound.
When I create a query using this exact statement in a different window, it returns with out issue:
SELECT
animal.AnimalId,
species.Code AS Species,
breed.Code AS Breed ,
country.CountryId AS CountryId ,
country.Code AS CountryCode ,
animal.Sex AS Sex ,
animalRegistration.Identifier AS RegNo ,
breed.Description + country.Code + animal.Sex + animalRegistration.Identifier AS FullRegNo,
thePrefix.Prefix AS Prefix,
animal.Name AS Name,
thePrefix.Prefix + animal.Name AS FullName,
animal.Name AS EarTag1,
animal.DateOfBirth as DateOfBirth ,
0 as AnimalFlagCount
FROM dbo.Animal AS animal
LEFT JOIN dbo.Breed breed ON animal.BreedId = breed.BreedId
LEFT JOIN dbo.Species species ON species.SpeciesId = breed.SpeciesId
LEFT JOIN dbo.AnimalIdentity animalIdentity ON animalIdentity.AnimalId = animal.AnimalId
LEFT JOIN dbo.AnimalIdentity animalRegistration ON animalRegistration.AnimalId = animal.AnimalId and animalRegistration.IdentityTypeId = 2
LEFT JOIN dbo.Country country ON animalIdentity.CountryId = country.CountryId
LEFT JOIN dbo.AnimalPrefix animalPrefix ON animalPrefix.AnimalId = animal.AnimalId
LEFT JOIN dbo.Prefix thePrefix ON thePrefix.PrefixId = animalPrefix.PrefixId
where
animalRegistration.Identifier = '5573144'
Can anyone see why this is creating an issue? I realize it might not be possible with this much code, but I figured maybe I'm overlooking something big.
Thanks,
Are you maybe forgetting to concatenate #sFrom to #sSql before you execute it?
Try changing
SELECT #sFrom = ' FROM .....
to
SELECT #sSql = #sSql + ' FROM .....
You can also try inserting a print statement of the sql you are about to execute to make sure you are executing what you think you're executing. ...
Also, what is #sFrom declared as? Perhaps it's getting truncated right before the last join and hence the error?
Hope that helps

Left Join with Case Statement in Sql Server getting ERROR

SELECT
Camp.ID, Inst.StartDate, Ctype.CampaignType,
'Cert' + REPLACE(Ctype.CampaignType, ' ', '') AS CampaignType
FROM
CertCampaign Camp
LEFT JOIN
(SELECT
CASE WHEN CampaignType = 'CertAccounttoRole' THEN CertUserToAccount) t ON Inst.ID = t.InstanceId
LEFT JOIN
CertAccounttoRole ON Inst.ID = t.InstanceId
LEFT JOIN
CertCampaignType Ctype ON Ctype.ID = Camp.CampaignTypeId
LEFT JOIN
CertInstance Inst ON Inst.CampaignId = Camp.ID
Getting error:
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ')'.
You need an END in your case stmt, you will also have to name that column:
LEFT JOIN(select case when CampaignType='CertAccounttoRole'
then CertUserToAccount
end as InstanceId )t ON
Inst.ID=t.InstanceId