Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an odd error, SQL Server query using `WITH` clause

Tags:

sql-server

The following query:

WITH      CteProductLookup(ProductId, oid)      AS      (         SELECT p.ProductID, p.oid         FROM [dbo].[ME_CatalogProducts] p      )  SELECT      rel.Name as RelationshipName,     pl.ProductId as FromProductId,     pl2.ProductId as ToProductId FROM      (     [dbo].[ME_CatalogRelationships] rel      INNER JOIN CteProductLookup pl      ON pl.oid = rel.from_oid     )      INNER JOIN CteProductLookup pl2      ON pl2.oid = rel.to_oid WHERE     rel.Name = 'BundleItem' AND     pl.ProductId = 'MX12345'; 

Is generating this error:

Msg 319, Level 15, State 1, Line 5 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.

On execution only. There are no errors/warnings in the sql statement in the managment studio.

Any ideas?

like image 233
Aren Avatar asked Apr 30 '10 18:04

Aren


People also ask

WHERE clause Cannot be used in a query with using?

The difference between the having and where clause in SQL is that the where clause cannot be used with aggregates, but the having clause can. The where clause works on row's data, not on aggregated data.

Which part of SQL query has an error?

The types of SQL errors we will look at are: Misspelling Commands. Forgetting Brackets and Quotes. Specifying an Invalid Statement Order.

Which one is the correct syntax for the WHERE clause in the SQL Server?

first_name = 'Sarah'; This SQL Server WHERE clause example uses the WHERE clause to join multiple tables together in a single SELECT statement. This SELECT statement would return all rows where the first_name in the employees table is 'Sarah'.

Which clause of SQL query can be used to?

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.


2 Answers

always use with statement like ;WITH then you'll never get this error. The WITH command required a ; between it and any previous command, by always using ;WITH you'll never have to remember to do this.

see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:

When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.

like image 93
KM. Avatar answered Sep 20 '22 17:09

KM.


;WITH      CteProductLookup(ProductId, oid)      AS  ... 
like image 40
gbn Avatar answered Sep 17 '22 17:09

gbn