CTE Recursion to get tree hierarchy

Try this: ;WITH items AS ( SELECT EstimateItemID, ItemType , 0 AS Level , CAST(EstimateItemID AS VARCHAR(255)) AS Path FROM EstimateItem WHERE ParentEstimateItemID IS NULL AND EstimateID = @EstimateID UNION ALL SELECT i.EstimateItemID, i.ItemType , Level + 1 , CAST(Path + ‘.’ + CAST(i.EstimateItemID AS VARCHAR(255)) AS VARCHAR(255)) FROM EstimateItem i INNER JOIN items itms … Read more

Common Table Expression, why semicolon?

To avoid ambiguity because WITH can be used elsewhere ..FROM..WITH (NOLOCK).. RESTORE..WITH MOVE.. It’s optional to terminate statements with ; in SQL Server Put together, the previous statement must be terminated before a WITH/CTE. To avoid errors, most folk use ;WITH because we don’t know what is before the CTE So DECLARE @foo int; WITH … Read more

CTE error: “Types don’t match between the anchor and the recursive part”

Exactly what it says: ‘name1’ has a different data type to ‘name’ + CAST((rn+1) as varchar(255)) Try this (untested) ;with cte as ( select 1 as rn, CAST(‘name1’ as varchar(259)) as nm union all select rn+1,nm = ‘name’ + CAST((rn+1) as varchar(255)) from cte a where rn<10) select * from cte Basically, you have to … Read more

Insert data in 3 tables at a time using Postgres

Use data-modifying CTEs: WITH ins1 AS ( INSERT INTO sample(firstname, lastname) VALUES (‘fai55’, ‘shaggk’) — ON CONFLICT DO NOTHING — optional addition in Postgres 9.5+ RETURNING id AS sample_id ) , ins2 AS ( INSERT INTO sample1 (sample_id, adddetails) SELECT sample_id, ‘ss’ FROM ins1 RETURNING user_id ) INSERT INTO sample2 (user_id, value) SELECT user_id, ‘ss2’ … Read more

MySQL “WITH” clause

Update: MySQL 8.0 is finally getting the feature of common table expressions, including recursive CTEs. Here’s a blog announcing it: http://mysqlserverteam.com/mysql-8-0-labs-recursive-common-table-expressions-in-mysql-ctes/ Below is my earlier answer, which I originally wrote in 2008. MySQL 5.x does not support queries using the WITH syntax defined in SQL-99, also called Common Table Expressions. This has been a feature … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)