Invalid Column in SQL SubQuery - sql-server-2012

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.

Related

What am I doing wrong with the loop use in SQL

I need to compare emails from tables and if they match I need to show some data from the third table and I'm trying to do that through a while loop which goes through the string of all emails and compares them and if its a match it should get the data from third table
Im pasting the query from pastebin here: https://pastebin.com/zyjcJngf
The part where I want to use the loop
select distinct Email,
CASE dbo.spValueToString((SELECT COUNT(*)
FROM tblEmailBlackList WHERE tblEmailBlackList.Email=LiveCampaign_SubscriberList_Email.Email AND tblEmailBlackList.PortalID>=-1))
WHEN 'Da' THEN
WHILE #vsi > 1
BEGIN
SET #testEmail = (SELECT LEFT(#resultCpy, CHARINDEX(',', #resultCpy) - 1)) --dobi prvi mail
SET #testEmail = (SELECT REPLACE(#testEmail, ' ', '')) --zbriše vse ' ' če obstajajo
SET #resultCpy = (SELECT SUBSTRING(#resultCpy, LEN(#testEmail) + 2, LEN(#resultCpy))) --odstani prvi mail
IF
#testEmail = Email
BREAK
ELSE
SET #vsi = #vsi - 1
END
SET #vsi = (SELECT LEN(#result) - LEN(REPLACE(#result, ',', '')) + 1)
SET #resultCpy = #result
(SELECT DISTINCT PortalLocalization.PortalName
FROM tblEmailBlackList
LEFT JOIN tblLiveCampaignSettings ON tblLiveCampaignSettings.ModuleID = tblEmailBlackList.ModuleID
LEFT JOIN PortalLocalization ON PortalLocalization.PortalID = tblEmailBlackList.PortalID AND PortalLocalization.CultureCode = 'sl-SI'
WHERE Email = #testEmail
AND tblEmailBlackList.PortalID >= 0
UNION
SELECT DISTINCT PortalLocalization.PortalName
FROM tblEmailBlackList
LEFT JOIN vw_TabModules ON vw_TabModules.ModuleID = tblEmailBlackList.ModuleID
LEFT JOIN PortalLocalization ON PortalLocalization.PortalID = vw_TabModules.PortalID AND PortalLocalization.CultureCode = 'sl-SI'
WHERE Email = #testEmail
AND tblEmailBlackList.PortalID = -1)
ELSE 'Ne' END
AS LocalBlockList
FROM LiveCampaign_SubscriberList_Email
The problem I have here is that I get an error when I add the loop in the code, but if I run the loop alone it works. I get the incorrect syntax near WHILE and The multi-part identifier "LiveCampaign_SubscriberList_Email.Email" could not be bound.
You cannot put a "WHILE" inside SELECT statement.
Try to treat your data before the SELECT, maybe inside a temp Table.

SQL 'as' Statement Issue

I'm having difficulty with the SQL 'as' statement. Based on what I've read and seen on YouTube, the 'as' or alias command can be used to rename columns.
Error:
System.Exception: Invalid object name 'Capprogram'
select main1.id as captempCaseMgmtMain_id , CapSSMatrix.Name as captempCaseMgmtMain_idSSMatrix , CapSSMatrix.datefrom as Date , CapSSMatrix.dateto as DateTo , Person.lastname +' , '+Person.firstname as Name , main1.date as captempCaseMgmtMain_id , Capprogram.program as captempCaseMgmtMain_idProgram from captempCaseMgmtMain main1 left join captempCaseMgmtMain main2 on main2.ssmgroup = main1.ssmgroup and main2.type = 3 JOIN CapSSMatrix on main1.idSSMatrix = CapSSMatrix.id JOIN Person on Person.id = main1.familymember JOIN Capprogram on capprogram.id = main1.idprogram where main1.type = 1 and isnumeric(main2.id)<> 1 and ((getdate() > capSSMatrix.dateto) ) and CapSSMatrix.id = '' order by main1.id desc at IMSE.UI.BaseEnginePage.GetDBValues() at IMSE.UI.Pages.Aspx_Pages.LoadPage() at IMSE.UI.Pages.Aspx_Pages.Page_Load(Object sender, EventArgs e)
This is the command/query I've tried. Any help is appreciated. Thank you in advance.
SELECT
main1.id AS captempCaseMgmtMain_id,
CapSSMatrix.Name AS captempCaseMgmtMain_idSSMatrix,
CapSSMatrix.datefrom AS Date,
CapSSMatrix.dateto AS DateTo,
Person.lastname + ', ' + Person.firstname AS Name,
main1.date AS captempCaseMgmtMain_id,
Capprogram.program AS captempCaseMgmtMain_idProgram
FROM
captempCaseMgmtMain main1
LEFT JOIN
captempCaseMgmtMain main2 ON main2.ssmgroup = main1.ssmgroup
AND main2.type = 3
JOIN
CapSSMatrix ON main1.idSSMatrix = CapSSMatrix.id
JOIN
Person ON Person.id = main1.familymember
JOIN
Capprogram ON capprogram.id = main1.idprogram
WHERE
main1.type = 1 AND
ISNUMERIC(main2.id) <> 1 AND
(GETDATE() > capSSMatrix.dateto) AND
CapSSMatrix.id = $CapSSMatrix.id
ORDER BY
main1.id DESC
This error suggests there is no object named Capprogram which I only see referenced in your join clause. I would confirm that this table exists and, if it does, use the fully qualified name.
It seems your table is not there in the schema. Find your table schema name by below query.
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
Then try to put schemaname.tablename
Also make sure that table is present in the database you are using
This code produces the following error:
Msg 126, Level 15, State 1, Line 24 Invalid pseudocolumn
"$CapSSMatrix".
This is because your $CapSSMatrix.id contains $ and server thinks it's a pseudocolumn, but it is not.
So if it's a table name, it should be quoted like this: [$CapSSMatrix], and if it's not just remove this $
you have to add LEFT JOIN to the table for example:
1- left join captempCaseMgmtMain main2
2- left join CapSSMatrix
3- left join Person
4- left join Capprogram

Complex Query Incorrect Syntax Error

I have tried to search for a solution to this but I have not been able to find one that fits this situation.
First I must say that my SQL is a lot rusty. The following query is the most complex one I have ever done to date.
Here is the query:
Declare #root varchar(Max)
set #root = ''
Select
ib.irrnum, ib.status, pu.probtype,
ib.submitby, ta.[Task Action], ib.area, co.cost,
rc.rootcause, ib.jobnum
From
tbl_irrbase ib
Left Join
tbl_cost co On ib.irrnum = co.irrnum
Left join
(Select Distinct probtype, irrnum
From tbl_probtype) pu On ib.irrnum = pu.irrnum
Left Join
(Select Distinct rootcause, irrnum
From tbl_rtcause) rc On ib.irrnum = rc.irrnum
Left Join
(Select TOP 1
(owner + Space(1) + Convert(varchar(10), senddate, 101) + Space(1) + taskitem) As 'Task Action',
irrnum
From
(select * From tbl_taskaction) ta
Order by
senddate Desc, sendtime Desc) ta On ib.irrnum = ta.irrnum
left Join
(Select [#root] = #root + rs.rootsource + Space(3), irrnum
From tbl_rtsource rs
Where rs.entrydate Between '10/04/2016' And '10/06/2016'
Select #root As 'Root Source') sr On ib.irrnum = sr.irrnum
Where
ib.submitedate between '09/28/2016' And '10/05/2016'
My problem is with the last Left Join line. If I take the entire Select statement out and run it in SSMS it runs fine, no errors. But when I try and run it in this query I get an error, red squiggly line under 'Select #root As' telling me the following:
Incorrect Syntax near 'Select'.
Expecting ')', EXCEPT, or UNION
I do not know how to fix this. If I remove this last 'Left Join' line the query runs fine.
Any ideas?
Instead of the last LEFT JOIN, try something like this:
CROSS APPLY (
SELECT (
SELECT rs.rootsource + Space(3)
From tbl_rtsource rs
Where rs.entrydate Between '10/04/2016' And '10/06/2016'
AND rs.irrnum=ib.irrnum
FOR XML PATH('')
) AS rootsource
) sr
Then include sr.rootsource in the columns of the first SELECT.

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

Update table with date conversion failing on Multi-Part Identifier

Thanks to the guys with suggestions on date conversion yesterday, I now have a working SELECT script.
Unfortunately, when I try to turn it into an UPDATE script, I get the dreaded
Msg 4104, Level 16, State 1, Line 25
The multi-part identifier "mbrProject.ID" could not be bound.
The entire script should insert the date from mbrProject into ProjectDates, for each matching ID (mbrProject.[ID] = ProjectDates.[Project_ID]), whilst resolving mixed US & UK format dates in mbrProject, due to users having incorrect country settings when updating the tables (not changeable from my end).
Update ProjectDates
SET ProjectDates.[Start_Date] =
(
select right([Start_Date],4) +
case
when len([Start_Date])=10 then
substring([Start_Date],4,2) + left([Start_Date],2)
else right('0' + left([Start_Date],firstIndex-1),2) +
right('0' + substring([Start_Date],firstIndex+1,secondIndex - firstIndex-1),2)
end
from
(
select mp.[Start_Date], charindex('/',mp.[Start_Date],1) firstIndex,
charindex('/',mp.[Start_Date],charindex('/',mp.[Start_Date],1)+1) secondIndex
from mbrProject mp
join ProjectDates pd
on mp.ID = pd.Project_ID
)A
where mbrProject.[ID] = ProjectDates.Project_ID
)
If I run ONLY the SELECT statement, it works fine, returning the correct values.
i.e Everything from
select right([Start_Date],4) +
case
down to
from mbrProject mp
join ProjectDates pd
on mp.ID = pd.Project_ID
)A
However, as soon as I try to wrap it up in the UPDATE statement, I get the error.
I know that this is down to syntax, but wherever I try to move stuff, I can't quite figure it out.
Any ideas please?
Thanks
Craig
Try this:
UPDATE PR
SET PR.[Start_Date] = A.[Corrected_Start_Date]
FROM ProjectDates PR
JOIN
(
SELECT
[Id],
RIGHT([Start_Date],4) +
CASE
WHEN len([Start_Date])=10
THEN substring([Start_Date],4,2) + LEFT([Start_Date],2)
ELSE RIGHT('0' + LEFT([Start_Date],firstIndex-1),2) +
RIGHT('0' + substring([Start_Date],firstIndex+1,secondIndex - firstIndex-1),2)
END [Corrected_Start_Date]
FROM
(
SELECT
[Id],
[Start_Date],
charindex('/',[Start_Date],1) firstIndex,
charindex('/',[Start_Date],charindex('/',[Start_Date],1)+1) secondIndex
FROM mbrProject
) S
) A
ON A.[ID] = PR.[Project_ID]
(
select mp.[Start_Date], charindex('/',mp.[Start_Date],1) firstIndex,
charindex('/',mp.[Start_Date],charindex('/',mp.[Start_Date],1)+1) secondIndex
from mbrProject mp
join ProjectDates pd
on mp.ID = pd.Project_ID
)A
At the end of the last line here, the names mp, pd, mbrProject and (the inner ProjectDates) no longer exist as table names or aliases. The only name applicable to this row set from here on is A, the alias you've provided.
So you need to include mp.ID in your select list, and then use A.ID in your outer comparison.
Also, not knowing what you're trying to do, I'd just want to make sure you're aware that ProductDates (the table being updated) and pd are referring to two separate instances of that table, an inner one and an outer one. I'm hoping that the final WHERE should be:
where A.[ID] = ProjectDates.Project_ID
The problem is that doing
Update ProjectDates
SET ProjectDates.[Start_Date] = (select ...)
you are trying to set one field of one row to the results of the sub-select statement, which, I presume, is returning multiple values.