Incorrect Syntax Merge Join - sql

Quite confused, SQL server 2012 identifies a syntax issue withing the MERGE subquery. However, when I run the subquery stand alone it works without any issues.
Have been staring at this for a while and need some fresh eyes.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near 'CM'.
Msg 102, Level 15, State 1, Line 25
Incorrect syntax near 'CS'.
USE [UDARepDBArchive]
INSERT INTO ZZZ_SCD
SELECT [Id]
,[ZZZ]
,[MMMMM]
,[VVVVVVV]
,Eff_Date
,End_Date = CONVERT(DATETIME2,END_DATE)
,Current_Flag
FROM
(MERGE ZZZ_SCD CM
USING (SELECT [ID] = GA.ACCOUNTID
,ZZZ = CASE
WHEN isnull(g.MMMMM,'0') = '0' OR ISNULL(g.VVVVVVV,'0') = '0'
THEN '0'
ELSE g.MMMMM /g.VVVVVVV
END
,MMMMM = G.MMMMM
,VVVVVVV = G.VVVVVVV
FROM UDAReporting.rbd.STRGroup G
LEFT OUTER JOIN UDAReporting.rbd.STRGroupAccount GA ON GA.GROUPID = G.GROUPID
) CS ON CM.ID = CS.ID
WHEN NOT MATCHED THEN
INSERT VALUES (cs.[Id]
,cs.[ZZZ]
,cs.[MMMMM]
,cs.[VVVVVVV]
,CONVERT(DATETIME2,GETDATE())
,'2199-10-01 00:00:00.000'
,'Y' )
WHEN MATCHED AND CM.Current_Flag = 'Y' AND (CM.ZZZ <> CS.ZZZ ) THEN
UPDATE SET CM.Current_Flag = 'N', CM.End_date = CONVERT(DATETIME2,GETDATE())
OUTPUT $Action Action_Out, cs.[Id]
,cs.[ZZZ]
,cs.[MMMMM]
,cs.[VVVVVVV]
,CONVERT(DATETIME2,GETDATE()) AS Eff_date
,'2199-10-01 00:00:00.000' End_Date
,'Y' Current_Flag
) AS MERGE_OUT
WHERE MERGE_OUT.Action_Out = 'UPDATE'

Appears the issue was caused by "SET COMPATIBILITY_LEVEL = 90" on the exsisting Databases, rather than upgrading an dealing with potential issues, I'll just be creating a new Database

Related

SELECT query using group by

I don't know why the following query is not working:
SELECT whs_code, pdt_code,case_dt_yyyymmdd, fresh_frozen_status,
SUM(qty_cases_on_hand)-Qty, SUM(qty_weight_on_hand)-Wt, operation
FROM
(
SELECT whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation,SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='RU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
)
WHERE operation='SU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation`
The error is :
Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'WHERE'.
To make it simple to understand what i am trying to do here, please see the example
I need data as result of
(SELECT x FROM tbl_table Where column y='SU')-(SELECT x FROM tbl_table Where column y='RU')
SELECT ru.whs_code,
ru.pdt_code,
ru.case_dt_yyyymmdd,
ru.fresh_frozen_status,
ru.operation,
ru.Qty - su.Qty AS Qty_Diff,
ru.Wt - su.Wt AS Wt_Diff
FROM
(
SELECT whs_code,
pdt_code,
case_dt_yyyymmdd,
fresh_frozen_status,
operation,
SUM(qty_cases_on_hand) AS Qty,
SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='RU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
) ru,
(
SELECT whs_code,
pdt_code,
case_dt_yyyymmdd,
fresh_frozen_status,
operation,
SUM(qty_cases_on_hand) AS Qty,
SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='SU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
) su
WHERE ru.whs_code = su.whs_code
AND ru.pdt_code = su.pdt_code
AND ru.case_dt_yyyymmdd = su.case_dt_yyyymmdd
AND ru.fresh_frozen_status = su.fresh_frozen_status
AND ru.operation = su.operation;

Update using CTE - Syntax error?

I'm trying to update a table using data contained in a CTE. Unfortunately I'm receiving a syntax error and I'm not quite sure why. The code currently is:
declare #period_id integer =
(
select period_id
from property.period
where getdate() between period_start and period_end
)
;with cte_reclassified as
(
select building_id ,
lease_id ,
scca_broad_category_code ,
scca_fine_categories_code ,
scca_notes_code ,
scca_sales_group_code ,
scca_uplift
from property.lease_period
where period_id = #period_id
)
update property.lease_period lp
from cte_reclassified r
set lp.scca_broad_category_code = r.scca_broad_category_code
where lp.lease_id = r.lease_id
and lp.building_id = r.building_id
The syntax error I'm receiving is:
Msg 102, Level 15, State 1, Line 21 Incorrect syntax near 'lp'.
Is there a way to do what i'm trying to attempt here? I've tried googling the subject but hit dead ends - any advice would be appreciated!
I think you want to take the "property" out of the UPDATE part of the statement (since you are updating through the CTE) and put the SET clause before the FROM:
update lease_period lp
set lp.scca_broad_category_code = r.scca_broad_category_code
from cte_reclassified r
where lp.lease_id = r.lease_id
You do not need to create alias on your update statement
On its syntax : Update [TableName] SET [ColumnName]='New Value' WHERE ColumnName='Filter'
have a look on this SO post on how it is done by #Robin Day:
SQL Server UPDATE from SELECT
Best Regards

Select From CTE using AS? SQL Server 2008

I'm trying to convert a PostgreSQL into SQL Server. But this query doesn't work.
What am I doing wrong? I tried to add a semicolon before WITH but no luck.
SELECT
member_a AS you, member_b AS mightknow, shared_connection,
CASE
WHEN (n1.member_job_country = n2.member_job_country AND n1.member_job_country = n3.member_job_country) THEN 'country in common'
WHEN (n1.member_unvan_id = n2.member_unvan_id AND n1.member_unvan_id = n3.member_unvan_id) THEN 'unvan in common'
ELSE 'nothing in common'
END AS reason
FROM (
WITH transitive_closure(member_a, member_b, distance, path_string, direct_connection) AS
(SELECT
member_a, member_b, 1 AS distance,
CAST(member_a as varchar(MAX)) + '.' + CAST(member_b as varchar(MAX)) + '.' AS path_string,
member_b AS direct_connection
FROM Member_Contact_Edges
WHERE member_a = 45046 -- set the starting node
UNION ALL
SELECT
tc.member_a, e.member_b, tc.distance + 1,
CAST(tc.path_string as varchar(MAX)) + CAST(e.member_b as varchar(MAX)) + '.' AS path_string,
tc.direct_connection
FROM Member_Contact_Edges AS e
JOIN transitive_closure AS tc ON e.member_a = tc.member_b
WHERE tc.path_string NOT LIKE '%' + CAST(e.member_b as varchar(MAX)) + '.%'
AND tc.distance < 2
)
SELECT
member_a, member_b,direct_connection AS shared_connection
FROM transitive_closure
WHERE distance = 2
) AS youmightknow
LEFT JOIN Members AS n1 ON youmightknow.member_a = n1.memberID
LEFT JOIN Members AS n2 ON youmightknow.member_b = n2.memberID
LEFT JOIN Members AS n3 ON youmightknow.shared_connection = n3.memberID
WHERE (n1.member_job_country = n2.member_job_country
AND n1.member_job_country = n3.member_job_country)
OR (n1.member_unvan_id = n2.member_unvan_id
AND n1.member_unvan_id = n3.member_unvan_id);
Error I get:
Msg 156, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 11
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.
Msg 102, Level 15, State 1, Line 34
Incorrect syntax near ')'.
Here is the reference; Graphs in the Database - SQL Meets Social Networks - Look at the facebook suggestion part at the bottom of the article.
Thanks in advance
The CTE declaration needs to go at the top. You can also have multiple CTEs declared and joined by commas rather than mixing CTEs and derived tables.
Try
;WITH
/*First CTE declaration*/
transitive_closure(member_a, member_b, distance, path_string, direct_connection)
AS
(
...
),
/*Second CTE declaration*/
youmightknow AS
(
SELECT member_a, member_b,direct_connection AS shared_connection
FROM transitive_closure
WHERE distance = 2
)
SELECT member_a AS you,
...
FROM youmightknow
Move your CTE definition to the beginning of your SQL statement. The keyword WITH appears once at the beginning of your statement to introduce one or more CTEs, which may then be referred to in the following SQL. Take a look at this CTE example, it will clear it up for you.

Not your usual "The multi-part identifier could not be bound" error

I have the following query, now the strange thing is if I run this query on my development and pre-prod server it runs fine. If I run it on production it fails.
I have figured out that if I run just the Select statement its happy but as soon as I try insert into the table variable it complains.
DECLARE #RESULTS TABLE
(
[Parent] VARCHAR(255)
,[client] VARCHAR(255)
,[ComponentName] VARCHAR(255)
,[DealName] VARCHAR(255)
,[Purchase Date] DATETIME
,[Start Date] DATETIME
,[End Date] DATETIME
,[Value] INT
,[Currency] VARCHAR(255)
,[Brand] VARCHAR(255)
,[Business Unit] VARCHAR(255)
,[Region] VARCHAR(255)
,[DealID] INT
)
INSERT INTO #RESULTS
SELECT DISTINCT
ClientName 'Parent'
,F.ClientID 'client'
,ComponentName
,A.DealName
,CONVERT(SMALLDATETIME , ISNULL(PurchaseDate , '1900-01-01')) 'Purchase Date'
,CONVERT(SMALLDATETIME , ISNULL(StartDate , '1900-01-01')) 'Start Date'
,CONVERT(SMALLDATETIME , ISNULL(EndDate , '1900-01-01')) 'End Date'
,DealValue 'Value'
,D.Currency 'Currency'
,ShortBrand 'Brand'
,G.BU 'Business Unit'
,C.DMRegion 'Region'
,DealID
FROM
LTCDB_admin_tbl_Deals A
INNER JOIN dbo_DM_Brand B
ON A.BrandID = B.ID
INNER JOIN LTCDB_admin_tbl_DM_Region C
ON A.Region = C.ID
INNER JOIN LTCDB_admin_tbl_Currency D
ON A.Currency = D.ID
INNER JOIN LTCDB_admin_tbl_Deal_Clients E
ON A.DealID = E.Deal_ID
INNER JOIN LTCDB_admin_tbl_Clients F
ON E.Client_ID = F.ClientID
INNER JOIN LTCDB_admin_tbl_DM_BU G
ON G.ID = A.BU
INNER JOIN LTCDB_admin_tbl_Deal_Components H
ON A.DealID = H.Deal_ID
INNER JOIN LTCDB_admin_tbl_Components I
ON I.ComponentID = H.Component_ID
WHERE
EndDate != '1899-12-30T00:00:00.000'
AND StartDate < EndDate
AND B.ID IN ( 1 , 2 , 5 , 6 , 7 , 8 , 10 , 12 )
AND C.SalesRegionID IN ( 1 , 3 , 4 , 11 , 16 )
AND A.BU IN ( 1 , 2 , 3 , 4 , 5 , 6 , 8 , 9 , 11 , 12 , 15 , 16 , 19 , 20 , 22 , 23 , 24 , 26 , 28 , 30 )
AND ClientID = 16128
SELECT ... FROM #Results
I get the following error
Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "Tbl1021.ComponentName" could not be bound.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "Tbl1011.Currency" could not be bound.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2454'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2461'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2491'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2490'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2482'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2478'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2477'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Col2475'.
EDIT - EDIT - EDIT - EDIT - EDIT - EDIT
through a process of elimination I have found that following and wondered if anyone can shed some light on this.
If I remove only the DISTINCT the query runs fine, add the DISTINCT and I get strange errors.
Also I have found that if I comment the following lines then the query runs with the DISTINCT what is strange is that none of the columns in the table LTCDB_admin_tbl_Deal_Components is referenced so I don't see how the distinct will affect that.
INNER JOIN LTCDB_admin_tbl_Deal_Components H
ON A.DealID = H.Deal_ID
Are any of these Views? I seem to remember getting weird errors like that after changing view definitions and not running sp_refreshview. I can't see the text "Tbl1021" anywhere so I'm assuming this is likely to be in a View definition?
If so there is a script here to refresh all views How do I create a stored procedure that calls sp_refreshview for each view in the database?
Ok I still don't know what caused this or what the correct answer is but here is what I ended up doing to get it fixed.
I created a duplicate of the offending table and populated it with a copy of the data.
I created all the same keys, indexes etc etc
Tested the query and guess what it worked.
So I made a backup of the data in the table dropped the offending table recreated it with all the keys, indexes etc etc and now order is restored.
All the queries that used to fail now works perfectly. Very strange
Eugene
Without running the code on my Development system, the first thing I would resolve is the inconsistent use of alias in the code
You should as good coding practice always where possible identify the object {owner}
I.E by using in this example prefix each object with the relevant alias A, B, C etc..
I.E for example ClientName 'Parent' make this A.ClientName 'Parent'
if this columns was in table aliased as A
SELECT DISTINCT
ClientName 'Parent'
,F.ClientID 'client'
,ComponentName
,A.DealName
,CONVERT(SMALLDATETIME , ISNULL(PurchaseDate , '1900-01-01')) 'Purchase Date'
,CONVERT(SMALLDATETIME , ISNULL(StartDate , '1900-01-01')) 'Start Date'
,CONVERT(SMALLDATETIME , ISNULL(EndDate , '1900-01-01')) 'End Date'
,DealValue 'Value'
,D.Currency 'Currency'
,ShortBrand 'Brand'
,G.BU 'Business Unit'
,C.DMRegion 'Region'
,DealID
FROM
LTCDB_admin_tbl_Deals A

Title: CTE error

I am getting these errors while executing the following SQL please help me
;WITH myCTE AS
(Select mcisi.* from
coke_packaged_item AS spi
JOIN coke_item AS si
ON si.coke_id = spi.coke_id
AND si.coke_item_id = spi.coke_item_id
AND si.shipper_flag = 'n'
JOIN merch_cat_import_coke_item AS mcisi
ON mcisi.coke_id = si.coke_id
AND mcisi.resolved_coke_item_id = si.coke_item_id
AND mcisi.cat_import_event_id = #cat_import_event_id
AND mcisi.accept_flag = 'y')
UPDATE coke_packaged_item
SET packaged_in_uom_id = (select resolved_packaged_unit_of_measure_id from myCTE where myCTE.coke_id = coke_id)
priced_in_uom_id = COALESCE((select resolved_weight_unit_of_measure_idfrom myCTE.coke_id = coke_id), #each_uom_id),
name = (select packaged_item_name from myCTE where myCTE.coke_id = coke_id),
package_weight = (select package_weight from myCTE where myCTE.coke_id = coke_id) ,
status_code = (select status_code from myCTE where myCTE.coke_id = coke_id) ,
last_modified_user_id = (select CASE WHEN last_modified_user_id = 42 THEN #posting_user_id ELSE last_modified_user_id END from myCTE where myCTE.coke_id = coke_id),
last_modified_timestamp = CURRENT_TIMESTAMP
and exists (select coke_id from coke_item AS si
where si.coke_id = spi.coke_id
AND si.coke_item_id = spi.coke_item_id
AND si.shipper_flag = 'n')
and exists (select coke_id from merch_cat_import_coke_item AS mcisi)
where mcisi.coke_id = si.coke_id
AND mcisi.resolved_coke_item_id = si.coke_item_id
AND mcisi.cat_import_event_id = #cat_import_event_id
AND mcisi.accept_flag = 'y'
The error message is:
Msg 102, Level 15, State 1, Procedure Sp_Name, Line 44
Incorrect syntax near 'priced_in_uom_id'.
Msg 102, Level 15, State 1, Procedure Sp_Name, Line 44
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Procedure Sp_Name, Line 45
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Procedure Sp_Name, Line 46
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Procedure Sp_Name, Line 47
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Procedure Sp_Name, Line 48
Incorrect syntax near ','.
Msg 156, Level 15, State 1, Procedure Sp_Name, Line 54
Incorrect syntax near the keyword 'and'.
Msg 156, Level 15, State 1, Procedure Sp_Name, Line 55
Incorrect syntax near the keyword 'where'.
My friend, I've been looking # your code, and so far, all I've really found are typing errors.
For instance,
* in the set clause, there is no comma between the set for packaged_in_uom_id and priced_in_uom_id
* in the subquery for priced_in_uom_id, there is no space in front of the from clause.
My advice is to adopt a stylized pattern for how you write you sql. The pattern I use says that
* each clause goes on its own line - select, from where, order by, group by
* each column goes on its own line
* list commas go BEFORE the item
when I began to format your code using these patterns, I began to see the problems.
I enforce these patterns using RedGate's SQL Refactor. It's the best SQL code formatter I've found.
Looks like you're missing a comma at the end of the first SET line
SET packaged_in_uom_id = (select resolved_packaged_unit_of_measure_id from myCTE where myCTE.coke_id = coke_id),
You're missing a Comma at line 44 after myCTE.coke_id = coke_id)
You're missing a comma here
SET packaged_in_uom_id = (select resolved_packaged_unit_of_measure_id from myCTE where myCTE.coke_id = coke_id) ,
Also on the next line down you're missing a space before the from and a where
select resolved_weight_unit_of_measure_idfrom myCTE.coke_id = coke_id
there might be other errors I'll leave you to find them
#SmartestVEGA You've posted loads of these sort of questions today. I suggest getting hold of a copy of SQL2008 Management Studio with its syntax checking. I pasted your query in and could see the issue very quickly.