SQL Server : merge using Join on Source Table fails to bind - sql

I am writing a SQL Server Merge statement but can't seem to get the syntax correct. Would someone please take a look to see where I'm going wrong?
Any help you can give is most appreciated.
What I have is two tables that I'd like to merge (w_materialmarketprices2 and d_component). My source (d_component) table requires me to do a join to a tax table (d_tax).
Everything works fine except for when I try to add the additional tax table into my join. The reason I need the tax table is because it contains a tax rate which I don't have in my d_component table (although I do have the corresponding tax code).
My comparison criteria between w_materialmarketprices2 and d_component includes the tax rate in the calculation.
Here's my code:
MERGE [DWH].[dbo].[w_materialmarketprices2] AS A
USING
(SELECT
[comp_code], [comp_desc], [comp_o_un], [comp_type],
[comp_ccy], [comp_tx], [comp_net_price], [comp_per],
[comp_doc_date], [comp_last_update], [comp_latest],
D.[tax_rate] AS TaxRate
FROM
[DWH].[dbo].[d_component]) AS B
INNER JOIN
[DWH].[dbo].[d_tax] AS D ON D.[tax_code] = B.[comp_tx]
ON
A.[mp_comp_code] = B.[comp_code] AND A.[mp_valid_date] = B.[comp_doc_date] AND B.[comp_net_price]>0 AND A.[mp_price_inc_vat] = ROUND(((B.[comp_net_price]/B.[comp_per])*(1+TaxRate),3) AND A.[mp_budget_actual] = 'PO Actual' AND B.[comp_type] ='P100' AND (left(B.[comp_code],1)='S' OR left(B.[comp_code],1)='R')
WHEN NOT MATCHED BY TARGET
THEN
INSERT ([mp_budget_actual], [mp_comp_code], [mp_comp_desc], [mp_unit], [mp_unit_qty], [mp_qualified_supplier], [mp_ccy], [mp_price_inc_vat], [mp_valid_date], [mp_last_update], [mp_latest])
VALUES ('PO Actual', B.[comp_code], B.[comp_desc], B.[comp_o_un], 1, 'Y', B.[comp_ccy], ROUND(((B.[comp_net_price]/B.[comp_per])*(1+TaxRate),3), B.[comp_doc_date], B.[comp_last_update], B.[comp_latest])
;
The error I'm getting is:
Msg 4145, Level 15, State 1, Line 20
An expression of non-boolean type specified in a context where a condition is expected, near ','.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'B'.
,D.[tax_rate] AS TaxRate shows up as underlined in red so I reckon the problem is something to do with that. I also get the message
The multi-part identifier "D.tax_rate" could not be bound
Thanks for your help in advance. Honkonger.

There is no reason to use a subquery in the USING clause, ie: don't put a SELECT in there:
MERGE [DWH].[dbo].[w_materialmarketprices2] AS A
USING
[DWH].[dbo].[d_component] AS B
INNER JOIN [DWH].[dbo].[d_tax] AS D ON D.[tax_code] = B.[comp_tx]
ON
A.[mp_comp_code] = B.[comp_code] .......

Related

Getting Error when using SQL With Common Table Expression (CTE)

I am new to SQL. I am trying to use SQL CTE but I keep getting the error:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ')'.
I am using ms-sql and reading the following blog for guide.
This is my query
WITH parents(BranchCode, SOLD,BANKERSCOUNT, [TARGET]) AS
(
SELECT MS.ParentBranchCode,
SUM(NP.SOLD) SOLD,
SUM(NP.BANKERSCOUNT) BANKERSCOUNT,
SUM(NP.[TARGET]) [TARGET]
FROM NEDLLIFEPARTICIPATION NP
INNER JOIN m_Structure MS
ON MS.BranchCode = NP.BranchCode
GROUP BY MS.ParentBranchCode, NP.Year, NP.MONTH, NP.ProductId
)
Does this give you an error? If not then it might be that you simply have not included a select statement following your common table expression. This would explain why your error is showing an issue with the closing bracket, it is just telling you (if my assumption is right) that your CTE is not being used in a query (and therefore will not compile).
WITH parents(BranchCode, SOLD,BANKERSCOUNT, [TARGET]) AS
(
SELECT MS.ParentBranchCode,
SUM(NP.SOLD) SOLD,
SUM(NP.BANKERSCOUNT) BANKERSCOUNT,
SUM(NP.[TARGET]) [TARGET]
FROM NEDLLIFEPARTICIPATION NP
INNER JOIN m_Structure MS
ON MS.BranchCode = NP.BranchCode
GROUP BY MS.ParentBranchCode, NP.Year, NP.MONTH, NP.ProductId
)
select * from parents;

SCCM2012 SQL Query has an error

I am creating an SQL query for my SCCM collection but I get that there is an error. It doesn't tell me what the error is and the rule looks ok for me.
Select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client, SMS_R_User.UniqueUserName
FROM SMS_R_System
JOIN SMS_UserMachineRelationship ON SMS_R_System.Name=SMS_UserMachineRelationship.MachineResourceName
JOIN SMS_R_User ON SMS_UserMachineRelationship.UniqueUserName=SMS_R_User.UniqueUserName
Where SMS_R_User.UniqueUserName in (select UniqueUserName from SMS_R_User where UserGroupName = "Domain\\GroupName")
Assuming that you haven't misspelled any column names the only thing that I can see that would throw an error is that maybe "Domain\\GroupName" should be 'Domain\\GroupName'? Double-quotes are normally used as quoted identifiers for objects while single-quotes denote string literals.
With the double quotes you would probably get an error like:
Msg 207, Level 16, State 1, Line ?? Invalid column name
'Domain\GroupName'.
Also, the subquery in the where clause looks unnecessary, this query should be equivalent (if I'm not misreading it):
SELECT
S.ResourceID,
S.ResourceType,
S.Name,
S.SMSUniqueIdentifier,
S.ResourceDomainORWorkgroup,
S.Client,
U.UniqueUserName
FROM SMS_R_System S
JOIN SMS_UserMachineRelationship UMR ON S.Name = UMR.MachineResourceName
JOIN SMS_R_User U ON UMR.UniqueUserName = U.UniqueUserName
WHERE U.UserGroupName = 'Domain\\GroupName'

Incorrect syntax near the keyword 'INNER'. On Simple SQL query?

I am getting an error on a query which worked for another similar task but in this case does not. All I want to do is copy the values from a column in one table to another:
UPDATE dbo.JobClients
SET JobClients.[Status] = dbo.Jobs.[Status]
INNER JOIN dbo.JobClients
ON dbo.Jobs.Id = dbo.JobClients.JobId
I added the square brackets around the "Status" because it was highlighting blue and I thought it may be a reserved word, but even so the error isn't pointing to that being the problem:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'INNER'.
Any ideas greatly appreciated!
You are missing the FROM clause. Try this instead:
UPDATE c
SET c.[Status] = j.[Status]
FROM dbo.JobClients AS c
INNER JOIN dbo.JobClients AS j ON j.Id = c.JobId

SQL Server Arithmetic overflow error converting expression to data type int

I have a trigger which executes after a record is inserted into a table. The trigger basically, calls a function and passes values from the insert into it. However, while it works some times, I also keep getting the following error:
Msg 8115, Level 16, State 2, Procedure UpdateNabersRating, Line 17
Arithmetic overflow error converting expression to data type int.
The trigger is as follows:
UPDATE BMS_Snapshot SET
NABERS = dbo.SetmetricsNABERSCalculation(
60,
tbl.NetFloorArea,
tbl.ElectricityCumulative,
tbl.GasCumulative,
tbl.ElectricityCumulativeMax,
tbl.GasCumulativeMax,
tbl.ElectricityMaxTotal,
tbl.GasMaxTotal,
tbl.NaturalGasConversionCubicMetersToMJ,
tbl.SuburbId)
FROM
(SELECT
Snap.SnapshotId AS SnapshotId,
Snap.ElectricityCumulative AS ElectricityCumulative,
Snap.GasCumulative AS GasCumulative,
Building.NetFloorArea AS NetFloorArea,
Building.NABERSElecTotalMax AS ElectricityMaxTotal,
Building.NABERSGasTotalMax AS GasMaxTotal,
Building.NABERSExpiry As Expiry,
NABERSTarget.ElecCumulativeMax AS ElectricityCumulativeMax,
NABERSTarget.GasCumulativeMax AS GasCumulativeMax,
[State].NaturalGasConversionCubicMetersToMJ AS NaturalGasConversionCubicMetersToMJ,
Suburb.SuburbId AS SuburbId
FROM inserted AS Snap
INNER JOIN AST_Building AS Building ON Snap.BuildingId = Building.BuildingId
INNER JOIN ESD_Suburb AS Suburb ON Building.SuburbId = Suburb.SuburbId
INNER JOIN ESD_State AS [State] ON Suburb.StateId = [State].StateId
INNER JOIN AST_NABERSTarget NABERSTarget ON Snap.BuildingId = NABERSTarget.BuildingId AND
Snap.TimeStamp = NABERSTarget.Timestamp
/*Where Snap.SnapshotId IN (Select inserted.SnapshotId FROM inserted)*/) AS tbl
WHERE tbl.SnapshotId = BMS_Snapshot.SnapshotId AND BMS_Snapshot.Range = 1
I've been playing around with it for a while, but can't seem to put my finger on the problem, particularly given it works sometimes.
Changed, arguments on function to FLOAT, instead of INT for two of the parameters.

Multi-part Identifier could not be bound - Update Query SQL Server 2005

SQL Server novice here.
UPDATE dbo.ObjectivesApproved
SET dbo.ObjectivesApproved.VAP = 'Y'
WHERE ((dbo.Approved.Cri_Group In ('X01' ,'X02' ,'X03' ,'X04' ,'X05' ,'X07' ,'X08' ,'X09' ,'X10' ,'X11' ,'X12' ,'X13' ,'X14')))
gives the following error
The multi-part identifier "dbo.Approved.Cri_Group" could not be bound.
What's causing the error?
Update: The above query was a result of trial and error. I'm updating an Access Application to SQL server, and having some trouble with the slightly different dialects of SQL
This is my original Query.
UPDATE dbo.Approved
INNER JOIN dbo.ObjectivesApproved ON dbo.Approved.ID = dbo.ObjectivesApproved.ID
SET dbo.ObjectivesApproved.VAP = 'Y'
WHERE ((dbo.Approved.Cri_Group
In ('X01' ,'X02' ,'X03' ,'X04' ,'X05' ,'X07' ,'X08' ,'X09' ,'X10' ,'X11' ,'X12' ,'X13' ,'X14')));
This gives the error - Incorrect syntax near the keyword 'INNER'
thanks
That would translate into
UPDATE
OA
SET
OA.VAP = 'Y'
FROM
dbo.Approved AS A
INNER JOIN dbo.ObjectivesApproved OA ON A.ID = OA.ID
WHERE
A.Cri_Group IN ('X01' ,'X02' ,'X03' ,'X04' ,'X05' ,'X07' ,'X08' ,'X09' ,'X10' ,'X11' ,'X12' ,'X13' ,'X14')
You are not specifying that the update also uses the Approved table anywhere, instead you just go ahead and use one if its columns.
On another note, your update looks logically flawed too as you'll update the ObjectivesApproved records irrespective of what they contain, i.e. there is no relation mentioned between ObjectivesApproved and Approved.