Left Join with Case Statement in Sql Server getting ERROR - sql

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

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.

Feature Summary using Rollup-

I am trying to modify a rollup query I found to use a select statement instead of a view. the rollup is:
select case when (grouping(lut_XXX_type_name) = 1) then 'ALL'
else ISNULL(lut_XXX_type_name, 'unknown')
end as lut_XXX_type_name,
case when (GROUPING(lut_YYY_status_name) = 1)then 'ALL'
ELSE ISNULL(lut_YYY_status_name, 'UNKNOWN')
end as lut_YYY_status_name,
SUM (ZZZ_quantity) as qtySum
from database.dbo.View_permitted
group by lut_XXX_type_name,lut_YYY_status_name with rollup
I want to replace the 'from database.dbo.View_permitted' with the following so I put it in Parenthesis:
SELECT dbo.WWW.WWW_id, dbo.WWW.WWW_grantee, dbo.YYY_entity.YYY_entity_apn, dbo.lut_YYY_status.lut_YYY_status_name,
dbo.lut_entity_type.lut_entity_type_name, dbo.lut_XXX_type.lut_XXX_type_name, dbo.county.county_name, dbo.ZZZ.ZZZ_quantity,
dbo.YYY.YYY_city, dbo.YYY.YYY_term, dbo.YYY.YYY_date_executed
FROM dbo.WWW INNER JOIN
dbo.YYY ON dbo.WWW.WWW_id = dbo.YYY.YYY_WWW_id INNER JOIN
dbo.lut_YYY_status ON dbo.YYY.YYY_lut_YYY_status_id = dbo.lut_YYY_status.lut_YYY_status_id INNER JOIN
dbo.ZZZ ON dbo.WWW.WWW_id = dbo.ZZZ.ZZZ_WWW_id INNER JOIN
dbo.lut_XXX_type ON dbo.ZZZ.ZZZ_lut_XXX_type_id = dbo.lut_XXX_type.lut_XXX_type_id INNER JOIN
dbo.YYY_entity ON dbo.YYY.YYY_id = dbo.YYY_entity.YYY_entity_YYY_id INNER JOIN
dbo.lut_entity_type ON dbo.YYY_entity.YYY_entity_lut_entity_type_id = dbo.lut_entity_type.lut_entity_type_id INNER JOIN
dbo.county ON dbo.WWW.WWW_county_id = dbo.county.county_id
WHERE (dbo.ZZZ.ZZZ_lut_XXX_type_id IN (20, 21, 22, 23, 24, 65, 66)) AND (dbo.county.county_name IN ('County1', 'county2')) AND
(dbo.YYY_entity.YYY_entity_WWW <> 0) AND (dbo.lut_YYY_status.lut_YYY_status_name IN ('Active', 'permitted’))
when I execute, I get the following error:
Msg 156, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'group'.
Msg 319, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
I have read threads regarding use of semicolon, I modified the end to be:
group by rollup(lut_XXX_type_name,lut_YYY_status_name)
but it is still not working...
Thanks for your help-
Try this:
group by rollup(lut_XXXXX_type_name, lut_YYYYY_status_name)
with rollup is used in some other databases.

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.

why sql case condition gives error

I do something like this which works fine :
select nameOfCols
from
FACost
inner join FAT as D on d.nid=a.atypeid
and
d.nid in (select item from SplitString('1,2,3,',','))
But when i use case to handle a situation where user dynamically may enter '' instead of '1,2,3,'. Then it gives error in my case condition
declare #selectedAssetTypeID varchar(50)='1,2,3,'
select nameOfCols
from
FACost
inner join FAT as D on d.nid=a.atypeid
and
case when #selectedAssetTypeID<>'' then d.nid in (select item from SplitString( #selectedAssetTypeID,',')) else d.nid=1 end //error causing lines
errors are:
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'in'.
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'else'.
Use and and or conditions instead of a case expression. The case expression as you have it is assigning a value (else d.nid=1) or checking for a true/false condition (d.nid in (select item from SplitString( #selectedAssetTypeID,','))).
and (
(#selectedAssetTypeID <>'' and d.nid in (select item from SplitString( #selectedAssetTypeID,',')) )
or (d.nid=1)
)
you cannot use in clause with case statement. because Case has to return one value per statement (either true or false)
either you can split your queries in two blocks or you can use "OR" clause.
IF #selectedAssetTypeID = " "
BEGIN
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where d.nid = 1
END
ELSE
BEGIN
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where d.nid IN
(select item from SplitString( #selectedAssetTypeID,','))
END
You can also use "OR" clause
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where ((#selectedAssetTypeID <>'' and d.nid in (select item from SplitString(#selectedAssetTypeID,',')))
or (d.nid=1))
link for the discussion about the similar issue is below
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bc8a7a0b-1980-4481-a2df-6a5fde38f362/in-clause-in-case-statement?forum=sqlgetstarted

How to fix error 102 on SQL Server

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 ')'.