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

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;

Related

Why do I have an 'invalid column name' when I try to sum two columns with alias that contains a space? [duplicate]

I've create 3 computed columns as alias and then used the aliased columns to calculate the total cost. This is the query:
SELECT TOP 1000 [Id]
,[QuantityOfProduct]
,[Redundant_ProductName]
,[Order_Id]
,(CASE
WHEN [PriceForUnitOverride] is NULL
THEN [Redundant_PriceForUnit]
ELSE
[PriceForUnitOverride]
END
) AS [FinalPriceForUnit]
,(CASE
WHEN [QuantityUnit_Override] is NULL
THEN [Redundant_QuantityUnit]
ELSE
[QuantityUnit_Override]
END
) AS [FinalQuantityUnit]
,(CASE
WHEN [QuantityAtomic_Override] is NULL
THEN [Redundant_QuantityAtomic]
ELSE
[QuantityAtomic_Override]
END
) AS [Final_QuantityAtomic]
--***THIS IS WHERE THE QUERY CREATES AN ERROR***--
,([QuantityOfProduct]*[FinalPriceForUnit]*
([Final_QuantityAtomic]/[FinalQuantityUnit])) AS [Final_TotalPrice]
FROM [dbo].[ItemInOrder]
WHERE [IsSoftDeleted] = 0
ORDER BY [Order_Id]
The console returns this ERROR message:
Msg 207, Level 16, State 1, Line 55
Invalid column name 'FinalPriceForUnit'.
Msg 207, Level 16, State 1, Line 55
Invalid column name 'Final_QuantityAtomic'.
Msg 207, Level 16, State 1, Line 55
Invalid column name 'FinalQuantityUnit'.
If I remove the "AS [Final_TotalPrice]" alias computed column, no error occurs, but I need the total price. How can I solve this issue? It seems as the other aliases have not been created when the Final_TotalPrice is reached.
You can't use table aliases in the same select. The normal solution is CTEs or subqueries. But, SQL Server also offers APPLY. (Oracle also supports APPLY and other databases such as Postgres support lateral joins using the LATERAL keyword.)
I like this solution, because you can create arbitrarily nested expressions and don't have to worry about indenting:
SELECT TOP 1000 io.Id, io.QuantityOfProduct, io.Redundant_ProductName,
io.Order_Id,
x.FinalPriceForUnit, x.FinalQuantityUnit, x.Final_QuantityAtomic,
(x.QuantityOfProduct * x.FinalPriceForUnit * x.Final_QuantityAtomic / x.FinalQuantityUnit
) as Final_TotalPrice
FROM dbo.ItemInOrder io OUTER APPLY
(SELECT COALESCE(PriceForUnitOverride, Redundant_PriceForUnit) as FinalPriceForUnit,
COALESCE(QuantityUnit_Override, Redundant_QuantityUnit) as FinalQuantityUnit
COALESCE(QuantityAtomic_Override, Redundant_QuantityAtomic) as Final_QuantityAtomic
) x
WHERE io.IsSoftDeleted = 0
ORDER BY io.Order_Id ;
Notes:
I don't find that [ and ] help me read or write queries at all.
COALESCE() is much simpler than your CASE statements.
With COALESCE() you might consider just putting the COALESCE() expression in the final calculation.
You can't use an alias in the same select. What you can do is find the value in subquery and then use it outside in the expression (or may be repeated the whole case statement in your expression). Also, use COALESCE to instead of CASE.
select t.*,
([QuantityOfProduct] * [FinalPriceForUnit] * ([Final_QuantityAtomic] / [FinalQuantityUnit])) as [Final_TotalPrice]
from (
select top 1000 [Id],
[QuantityOfProduct],
[Redundant_ProductName],
[Order_Id],
coalesce([PriceForUnitOverride], [Redundant_PriceForUnit]) as [FinalPriceForUnit],
coalesce([QuantityUnit_Override], [Redundant_QuantityUnit]) as [FinalQuantityUnit],
coalesce([QuantityAtomic_Override], [Redundant_QuantityAtomic]) as [Final_QuantityAtomic]
from [dbo].[ItemInOrder]
where [IsSoftDeleted] = 0
order by [Order_Id]
) t;

What is the syntax problem here using this subquery inside where clause

SELECT p.pnum, p.pname
FROM professor p, class c
WHERE p.pnum = c.pnum AND c.cnum = CS245 AND (SELECT COUNT(*) FROM (SELECT MAX(m.grade), MAX(m.grade) - MIN(m.grade) AS diff
FROM mark m WHERE m.cnum = c.cnum AND m.term = c.term AND m.section = c.section AND diff <= 20)) = 3
Incorrect syntax near ')'. Expecting AS, FOR_PATH, ID, or QUOTED_ID.
Consider the following example:
SELECT COUNT(1)
FROM SYSCAT.TABLES T
WHERE
(
-- SELECT COUNT(1)
-- FROM
-- (
SELECT COUNT(1)
FROM SYSCAT.COLUMNS C
WHERE C.TABSCHEMA=T.TABSCHEMA AND C.TABNAME=T.TABNAME
-- )
) > 50;
The query above works as is. But the problem is, that if you uncomment the commented out lines, you get the following error message: "T.TABNAME" is an undefined name. and least in Db2 for Linux, Unix and Windows.
You can't push external to the sub-select column references too deeply.
So, your query is incorrect.
It's hard to correct it, until you provide the task description with data sample and the result expected.
I can see a potential syntax errors: It seems that CS245 refers to a value c.cnum may take and not a column name. If that is the case, it should be enclosed in single quotes.

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

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] .......

SQL query works even with wrong syntax

I am running a SQL query in stored procedure which is like following
SELECT
t1.id,t2.Name
FROM
table1 t1 , table2 t2 ,table2 t3,table4 t4
WHERE
t1.id=t3.t4.id
this query gets executed on SQL server 2008 when its compatible with SQL server 2000 but if we turn OFF the compatibility with SQL server 2000 then this Query gives syntax error which is expected.
Can some one help me to understand why this is happeneing ? thanks in advance
Original query:
SELECT
ConfigID , LocationDesc + '-' + LOBTeamDesc LocLOBTeamSource
FROM Config CONFIG , Location_LOBTeam LOCLOB , Location LOC , LOBTeam LOB, System SRC
WHERE CONFIG.LocationLOBTeamID = LOC.LOB.LocationLOBTeamID
AND CONFIG.SourceSystemID = SRC.SystemID
AND LOCLOB.LocationID = LOC.LocationID
AND LOCLOB.LOBTeamID = LOB.LOBTeamID
AND (GETDATE() BETWEEN CONFIG.effectiveDate AND CONFIG.EndDate
OR CONFIG.EndDate IS NULL)
ORDER BY
LOC.LocationCode
I think that original query, with current standard join syntax applied would be this:
SELECT
ConfigID
, LocationDesc + '-' + LOBTeamDesc LocLOBTeamSource
FROM Config CONFIG
INNER JOIN Location_LOBTeam LOCLOB
ON CONFIG.LocationLOBTeamID = LOCLOB.LocationLOBTeamID
INNER JOIN Location LOC
ON LOCLOB.LocationID = LOC.LocationID
INNER JOIN LOBTeam LOB
ON LOCLOB.LOBTeamID = LOB.LOBTeamID
INNER JOIN [System] SRC
ON CONFIG.SourceSystemID = SRC.SystemID
WHERE (GETDATE() BETWEEN CONFIG.effectiveDate AND CONFIG.EndDate
OR CONFIG.EndDate IS NULL)
ORDER BY
LOC.LocationCode
Perhaps this will help.
+EDIT
"System" as a table name, could that be a problem? Suggest you try it as [System]
+EDIT2
The original is given with this: LOC.LOB.LocationLOBTeamID but that appears to be an error as there is an alias LOCLOB
I think below post from msdn answers this issue Compatibility Levels and Stored Procedures
in the above post the point number 3 under section "Differences Between Compatibility Level 80 and Level 90" states "WHEN binding the column references in the ORDER BY list to the columns defined in the SELECT list, column ambiguities are ignored and column prefixes are sometimes ignored. This can cause the result set to return in an unexpected order."
on my database I am using compatibility level 80 i.e 2000 thats why it runs smoothly with the given syntax but when I remove this compatibility and make it to 100 i.e. 2008/R2 script gives syntax error which is expected

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