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
Related
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.
I'm writing SQL against a Progress 10.2B07 database and am getting the following error "Column 'OUTERINVOICEHEADER.MEMBERID' cannot be found or is not specified for query (13865).
Here is the query:
select concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) as MemberID,
sum(OuterInvoiceHeader.net_weight) as TotalInvoicePounds,
sum(OuterInvoiceHeader.net_weight / 2000) as TotalTons,
sum(OuterInvoiceHeader.invoice_amt) as InvoiceAmount,
sum(InvoiceSurcharges.Surcharge) as Surcharges,
sum(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) as Total,
sum(Returns.qty_received) as PoundsReturned
from AXS.PUB.ivc_header OuterInvoiceHeader
inner join
(select m.invoice_nbr, sum(m.extension) Surcharge from AXS.PUB.ivc_mchgs m
inner join
AXS.PUB.ivc_header h
on h.invoice_nbr = m.invoice_nbr
group by m.invoice_nbr) InvoiceSurcharges
on OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
left outer join
(select concat(substring(ReturnHeader.ship_to_nbr, 1, 6)+'-',InnerInvoiceHeader.sold_to_cust_seq) as ReturnMemberID,
ReturnHeader.invoice_nbr as ReturnInvoiceNum,
qty_received
from AXS.PUB.return_hdr ReturnHeader
inner join
AXS.PUB.ivc_header InnerInvoiceHeader
on ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
inner join AXS.PUB.return_line ReturnLine
on ReturnHeader.claim_nbr = ReturnLine.claim_nbr
where ReturnInvoiceNum = '0001010914'
group by ReturnMemberID, ReturnInvoiceNum, qty_received) Returns
on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
where OuterInvoiceHeader.sold_to_cust_nbr = '000837' and OuterInvoiceHeader.invoice_date between '06/01/2016' and '06/30/2016' and OuterInvoiceHeader.invoice_status = '5804' and OuterInvoiceHeader.invoice_type='5601'
group by MemberID
The problem is in the left join; the commented out on clause "on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum" will work if uncommented. The "on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID" clause gives me the error.
What I don't understand is that both of these reference a column in the top SELECT statement, the only difference is that one is a concatenation and the other is not.
I hope that I just can't see the forest for the trees here and the answer is simple, so if anyone has any suggestions or questions I'm all ears.
try this:
I replaced the references to the alias MemberID to be the actual concatinated columns CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq)
SELECT CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) AS MemberID
, SUM(OuterInvoiceHeader.net_weight) AS TotalInvoicePounds
, SUM(OuterInvoiceHeader.net_weight / 2000) AS TotalTons
, SUM(OuterInvoiceHeader.invoice_amt) AS InvoiceAmount
, SUM(InvoiceSurcharges.Surcharge) AS Surcharges
, SUM(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) AS Total
, SUM(Returns.qty_received) AS PoundsReturned
FROM AXS.PUB.ivc_header OuterInvoiceHeader
INNER JOIN
(SELECT m.invoice_nbr
, SUM(m.extension) Surcharge
FROM AXS.PUB.ivc_mchgs m
INNER JOIN AXS.PUB.ivc_header h ON h.invoice_nbr = m.invoice_nbr
GROUP BY m.invoice_nbr) InvoiceSurcharges ON OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
LEFT OUTER JOIN
(SELECT CONCAT(SUBSTRING(ReturnHeader.ship_to_nbr, 1, 6)+'-', InnerInvoiceHeader.sold_to_cust_seq) AS ReturnMemberID
, ReturnHeader.invoice_nbr AS ReturnInvoiceNum
, qty_received
FROM AXS.PUB.return_hdr ReturnHeader
INNER JOIN AXS.PUB.ivc_header InnerInvoiceHeader ON ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
INNER JOIN AXS.PUB.return_line ReturnLine ON ReturnHeader.claim_nbr = ReturnLine.claim_nbr
WHERE ReturnInvoiceNum = '0001010914'
GROUP BY ReturnMemberID
, ReturnInvoiceNum
, qty_received) Returns ON CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
WHERE OuterInvoiceHeader.sold_to_cust_nbr = '000837'
AND OuterInvoiceHeader.invoice_date BETWEEN '06/01/2016' AND '06/30/2016'
AND OuterInvoiceHeader.invoice_status = '5804'
AND OuterInvoiceHeader.invoice_type = '5601'
GROUP BY CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq);
Basically you need to keep in mind the order which SQL statements are executed:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
That's a computed column alias and thus the error. You should consider using the entire expression rather like
on concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
Instead of on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID. As well, change any other place where you are using the same alias. You can and should use that alias only in a outer query and not in the same query.
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
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 ')'.
Here is my select statement. What I'm trying to do is if an account has more than one ID, I want the phone number to be NULL, ELSE I want the phone number to = phone_number_formatted:
SELECT
v_returned_inventory.order_id,
v_live_inventory.inet_event_description,
v_live_inventory.event_time,
v_cust_phone.phone_number_formatted,
v_live_inventory.event_date,
v_returned_inventory.section_name,
v_returned_inventory.add_usr,
v_live_inventory.num_seats,
v_returned_inventory.acct_id,
v_live_inventory.class_name,
AT_trans_for_emailTrigger.email_addr,
AT_trans_for_emailTrigger.cust_name_id,
premclub.name_first + ' ' + premclub.name_last AS name
FROM
v_returned_inventory
INNER JOIN
v_live_inventory
ON
LEFT(v_returned_inventory.event_name, 6) = LEFT(v_live_inventory.event_name, 6)
AND v_returned_inventory.orderNumber = v_live_inventory.other_info_1 INNER JOIN
AT_trans_for_emailTrigger
ON v_returned_inventory.order_id = AT_trans_for_emailTrigger.order_id
LEFT OUTER JOIN
v_cust_phone
on v_cust_phone.acct_id = v_returned_inventory.acct_id
LEFT OUTER JOIN
OPENQUERY(premclub, 'select name_first, name_last, cust_name_id from dba.v_cust_name') AS premclub
ON AT_trans_for_emailTrigger.cust_name_id = premclub.cust_name_id,
**CASE
WHEN (select
count(cust_name_id)
from
v_cust_phone) > 1 then null
else v_cust_phone.phone_number_formatted
END**
You have the CASE statement in the wrong place, it needs to be in the SELECT. Based on what you currently have, it appears that you might be able to do something like this:
SELECT v_returned_inventory.order_id,
v_live_inventory.inet_event_description,
v_live_inventory.event_time,
case when phone.cnt > 1 then null else v_cust_phone.phone_number_formatted end phone_number_formatted,
v_live_inventory.event_date,
v_returned_inventory.section_name,
v_returned_inventory.add_usr,
v_live_inventory.num_seats,
v_returned_inventory.acct_id,
v_live_inventory.class_name,
AT_trans_for_emailTrigger.email_addr,
AT_trans_for_emailTrigger.cust_name_id,
premclub.name_first + ' ' + premclub.name_last AS name
FROM v_returned_inventory
INNER JOIN v_live_inventory
ON LEFT(v_returned_inventory.event_name, 6) = LEFT(v_live_inventory.event_name, 6)
AND v_returned_inventory.orderNumber = v_live_inventory.other_info_1
INNER JOIN AT_trans_for_emailTrigger
ON v_returned_inventory.order_id = AT_trans_for_emailTrigger.order_id
LEFT OUTER JOIN v_cust_phone
on v_cust_phone.acct_id = v_returned_inventory.acct_id
LEFT OUTER JOIN
(
select count(cust_name_id) cnt, cust_name_id
from v_cust_phone
group by cust_name_id
) phone
on v_cust_phone.cust_name_id = phone.cust_name_id
LEFT OUTER JOIN OPENQUERY(premclub, 'select name_first, name_last, cust_name_id from dba.v_cust_name') AS premclub
ON AT_trans_for_emailTrigger.cust_name_id = premclub.cust_name_id