T-SQL Insert - Select in Table variable is very slow - tsql

I have a table variable and I am inserting in it some values using the "Insert Into - Select" statement. The select is a combination of few joins, and when it is executed separately it takes 3 seconds. The problem is that the whole code takes 3-4 minutes to executed. I wonder is there a particular reason for this.
This is the my table variable declaration:
DECLARE #Result TABLE
(
ProductID NVARCHAR(25) PRIMARY KEY
,ProductName NVARCHAR(100)
,ProductCategoryID TINYINT
,ProductCategory NVARCHAR(50)
,ProductSubCategoryID TINYINT
,ProductSubCategory NVARCHAR(50)
,BrandID TINYINT
,Brand NVARCHAR(50)
)
I have an other table variable which I initialize with some data, and this is its structure:
DECLARE #TempTable TABLE
(
ProtoSurveyID INT,
ProductID NVARCHAR(25) PRIMARY KEY
)
and the following code is my problem statement (insert into - select):
INSERT INTO #Result (ProductID,ProductName,ProductCategoryID,ProductCategory,ProductSubCategoryID,ProductSubCategory,BrandID,Brand)
SELECT
Products.ProductID AS ProductID
,Products.ProductName AS ProductName
,ProductCategories.ProductCategoryID AS ProductCategoryID
,ProductCategories.ProductCategory AS ProductCategory
,ProductSubCategories.ProductSubCategoryID AS ProductSubCategoryID
,ProductSubCategories.ProductSubCategory AS ProductSubCategory
,Brands.BrandID AS BrandID
,Brands.Brand AS Brand
FROM
(
SELECT
CAST(A.Col001 AS tinyint) AS ProductCategoryID
,CAST(A.Col002 AS tinyint) AS BrandID
,CAST(A.Col003 AS nvarchar(25)) AS ProductID
,CAST(A.Col004 AS nvarchar(100)) AS ProductName
,CAST(A.Col006 As tinyint) AS ProductSubCategoryID
,B.ProtoSurveyID
FROM DataSetsMaterializedDataSqlvariant A
INNER JOIN #TempTable B
ON B.ProductID=CAST(A.Col003 AS nvarchar(25))
WHERE DataSetsMaterializedInternalRowsetID = 3
) Products
INNER JOIN
(
SELECT CAST(A.Col001 AS tinyint) AS BrandID
, CAST(A.Col002 AS nvarchar(50)) AS Brand
FROM DataSetsMaterializedDataSqlvariant A
WHERE DataSetsMaterializedInternalRowsetID = 1
)Brands On Products.BrandID=Brands.BrandID
INNER JOIN
(
SELECT CAST(A.Col001 AS tinyint) AS ProductCategoryID
,CAST(A.Col002 AS nvarchar(50)) AS ProductCategory
FROM DataSetsMaterializedDataSqlvariant A
WHERE DataSetsMaterializedInternalRowsetID = 2
) ProductCategories On Products.ProductCategoryID=ProductCategories.ProductCategoryID
INNER JOIN
(
SELECT CAST(A.Col001 AS tinyint) AS ProductSubCategoryID
, CAST(A.Col002 AS nvarchar(50)) AS ProductSubCategory
FROM DataSetsMaterializedDataSqlvariant A
WHERE DataSetsMaterializedInternalRowsetID = 11
) ProductSubCategories on Products.ProductSubCategoryID=ProductSubCategories.ProductSubCategoryID
As I told before, if I comment the insert line the query takes 3 seconds, otherwise - a very long time.
EDIT: Here is my execution plan - most of the cost is table scan, but why it takes so many time when insert is make, and happens to quick without it?
The follow is my new inline function:
CREATE FUNCTION [dbo].[fn_XxCustom_RetailAudits_GetProductsForFilter]
(
#SecurityObjectUserID BIGINT
)
RETURNS TABLE
AS
RETURN
WITH CTE(ProtoSurveyID,ProductID) AS
(
SELECT DISTINCT CAST(B.ProtoSurveyID AS INT)
,CAST(A.Col002 AS NVARCHAR(25)) AS ProductID
FROM DataSetsMaterializedDataSqlvariant A
JOIN SurveyInstances B ON A.Col001=B.SurveyInstanceID AND CAST(B.ProtoSurveyID AS INT) IN (SELECT ProtoSurveyID FROM dbo.fn_Filter_GetProtoSurveysAllowedShort(#SecurityObjectUserID, 'CLIENTACCESS',NULL))
WHERE DataSetsMaterializedInternalRowsetID = 5
)
SELECT
Products.ProductID AS ProductID
,Products.ProductName AS ProductName
,ProductCategories.ProductCategoryID AS ProductCategoryID
,ProductCategories.ProductCategory AS ProductCategory
,ProductSubCategories.ProductSubCategoryID AS ProductSubCategoryID
,ProductSubCategories.ProductSubCategory AS ProductSubCategory
,Brands.BrandID AS BrandID
,Brands.Brand AS Brand
FROM
(
SELECT
CAST(A.Col001 AS tinyint) AS ProductCategoryID
,CAST(A.Col002 AS tinyint) AS BrandID
,CAST(A.Col003 AS nvarchar(25)) AS ProductID
,CAST(A.Col004 AS nvarchar(100)) AS ProductName
,CAST(A.Col006 As tinyint) AS ProductSubCategoryID
,B.ProtoSurveyID
FROM CTE B
INNER JOIN DataSetsMaterializedDataSqlvariant A
ON B.ProductID=CAST(A.Col003 AS nvarchar(25))
WHERE DataSetsMaterializedInternalRowsetID = 3
) Products
INNER JOIN
(
SELECT CAST(A.Col001 AS tinyint) AS BrandID
,CAST(A.Col002 AS nvarchar(50)) AS Brand
FROM DataSetsMaterializedDataSqlvariant A
WHERE DataSetsMaterializedInternalRowsetID = 1
)Brands On Products.BrandID=Brands.BrandID
INNER JOIN
(
SELECT CAST(A.Col001 AS tinyint) AS ProductCategoryID
,CAST(A.Col002 AS nvarchar(50)) AS ProductCategory
FROM DataSetsMaterializedDataSqlvariant A
WHERE DataSetsMaterializedInternalRowsetID = 2
) ProductCategories On Products.ProductCategoryID=ProductCategories.ProductCategoryID
INNER JOIN
(
SELECT CAST(A.Col001 AS tinyint) AS ProductSubCategoryID
,CAST(A.Col002 AS nvarchar(50)) AS ProductSubCategory
FROM DataSetsMaterializedDataSqlvariant A
WHERE DataSetsMaterializedInternalRowsetID = 11
) ProductSubCategories on Products.ProductSubCategoryID=ProductSubCategories.ProductSubCategoryID
GO
I runs slowly again. Any ideas how to optimize it?

Queries that insert into table variables can't have a parallel plan.
Try using a #temp table instead to allow the SELECT to be parallelised.

Related

Return previous value before null value

I'm currently querying a table with missing indexes.
Here is some sample data:
id dStartDate
126 2010-04-22 00:00:00.000
127 NULL
128 2010-04-29 00:00:00.000
129 2010-05-03 00:00:00.000
130 NULL
131 NULL
132 NULL
133 2010-04-29 00:00:00.000
134 NULL
135 NULL
136 2010-04-29 00:00:00.000
137 NULL
138 NULL
139 2010-04-29 00:00:00.000
140 NULL
141 2010-04-29 00:00:00.000
142 2010-04-29 00:00:00.000
143 NULL
144 NULL
I use the following script to get the missing indexes:
declare #id int
declare #maxid int
set #id = 1
select #maxid = max(idJCMaster) from _btblJCMaster
declare #IDseq table (id int)
while #id < #maxid --whatever you max is
begin
insert into #IDseq values(#id)
set #id = #id + 1
end
select
s.id
from #IDseq s
left join _btblJCMaster t on s.id = t.idJCMaster
where t.idJCMaster is null
The above works perfect, however, I would like to see the previous record (that is not null) date, to have an idea when this record was deleted...
I altered the above script to look like this:
declare #id int
declare #maxid int
set #id = 1
select #maxid = max(idJCMaster) from _btblJCMaster
declare #IDseq table (id int)
while #id < #maxid --whatever you max is
begin
insert into #IDseq values(#id)
set #id = #id + 1
end
select
s.id
, t.dStartDate
from #IDseq s
left join _btblJCMaster t on s.id = t.idJCMaster
The results I get looks like this:
As can be seen, sometimes there is more than on record missing for those particular indexes...
I'm not really sure how to alter the script to show me the previous date (before null).
In this example, my expected results would be:
Please assist with the expected results?
Your assistance will be much appreciated!
Edit
After the assistance of Ankit, tried the following (his answer):
declare #id int
declare #maxid int
set #id = 1
select #maxid = max(idJCMaster) from _btblJCMaster
declare #IDseq table (id int)
while #id < #maxid --whatever you max is
begin
insert into #IDseq values(#id)
set #id = #id + 1
end
select
s.id
, (SELECT MAX(dStartDate)
FROM _btblJCMaster
WHERE id >= t1.idJCMaster) dStartDate
from #IDseq s
left join _btblJCMaster t1 on s.id = t1.idJCMaster
But I still receive NULLS.
I then proceeded to try his first answer, by altering the LAG function a bit and also adding LEAD, with 3 CTE's, but I still get NULLS:
declare #id int
declare #maxid int
set #id = 1
select #maxid = max(idJCMaster) from _btblJCMaster
declare #IDseq table (id int)
while #id < #maxid --whatever you max is
begin
insert into #IDseq values(#id)
set #id = #id + 1
end
;with cte (id, dStartDate, idJCMaster)
as
(
select
s.id
, ISNULL(dStartDate, isnull(LAG(dStartDate) OVER(order by s.id),LEAD(dStartDate) OVER(order by s.id)))
, IdJCMaster
from #IDseq s
left join _btblJCMaster t1 on s.id = t1.idJCMaster
)
, cte2 (id,dStartDate, idJCMaster)
as
(
select
id
, isnull(dStartDate,LAG(dStartDate) OVER(order by id))
, idJCMaster
from cte
)
, cte3 (id,dStartDate, idJCMaster)
as
(
select
id
, isnull(dStartDate,LEAD(dStartDate) OVER(order by id))
, idJCMaster
from cte2
)
select
id
, isnull(dStartDate,LAG(dStartDate) OVER(order by id))
from cte3
where idJCMaster is null
Is there no other easier way to accomplish this?
You can try something along this:
First we need a mockup table to simulate your issue. Please provide this yourself in your next question. It is always best to provide a self-running, stand-alone sample including DDL, INSERT and your own attempt. Such a simuation is called MCVE.
DECLARE #tbl TABLE(id INT, dStartDate DATE);
INSERT INTO #tbl VALUES
(126,'2010-04-22 00:00:00.000')
,(127,NULL)
,(128,'2010-04-29 00:00:00.000')
,(129,'2010-05-03 00:00:00.000')
,(130,NULL)
,(131,NULL)
,(132,NULL)
,(133,'2010-04-29 00:00:00.000')
,(134,NULL)
,(135,NULL)
,(136,'2010-04-29 00:00:00.000')
,(137,NULL)
,(138,NULL)
,(139,'2010-04-29 00:00:00.000')
,(140,NULL)
,(141,'2010-04-29 00:00:00.000')
,(142,'2010-04-29 00:00:00.000')
,(143,NULL)
,(144,NULL);
--The query
WITH cte AS(SELECT id,dStartDate FROM #tbl WHERE dStartDate IS NOT NULL)
SELECT t.id
,A.gaplessStartDate
FROM #tbl t
CROSS APPLY(SELECT TOP 1 cte.dStartDate
FROM cte
WHERE cte.id<=t.id
ORDER BY cte.id DESC) A(gaplessStartDate);
The idea in short:
We use a CTE first to get a set with non-null rows only.
Now we can use APPLY to get the fitting row along with the id by calling the top-most of the smaller ids sorted in descending order.
The approach is sort of a triangle JOIN (Jeff Moden wrote a great article on this). Any row will need a correlated sub-query with an ORDER BY action.
Hint: With larger set this might be faster if you use an indexed temp table instead of the CTE.
You may try below query -
SELECT id, (SELECT MAX(dStartDate)
FROM YOUR_TABLE
WHERE id >= t1.id) dStartDate
FROM YOUR_TABLE t1;
Thank you #Shnugo for your assistance!
With your help, the following script gives me exactly what I required that works on my data set:
declare #id int
declare #maxid int
set #id = 1
select #maxid = max(idJCMaster) from _btblJCMaster
declare #IDseq table (id int)
while #id < #maxid --whatever you max is
begin
insert into #IDseq values(#id)
set #id = #id + 1
end
;with source (id,dStartDate)
as
(
select
s.id
, dStartDate
from #IDseq s
left join _btblJCMaster t1 on s.id = t1.idJCMaster
)
, cte AS(SELECT id,dStartDate FROM source WHERE dStartDate IS NOT NULL)
SELECT t.id
,A.gaplessStartDate
FROM source t
CROSS APPLY(SELECT TOP 1 cte.dStartDate
FROM cte
WHERE cte.id<=t.id
ORDER BY cte.id DESC) A(gaplessStartDate)
WHERE t.dStartDate IS NULL
order by id
This is just for other viewers to use, should you require it.

sql recursion: find tree given middle node

I need to get a tree of related nodes given a certain node, but not necessary top node. I've got a solution using two CTEs, since I am struggling to squeeze it all into one CTE :). Might somebody have a sleek solution to avoid using two CTEs? Here is some code that I was playing with:
DECLARE #temp AS TABLE (ID INT, ParentID INT)
INSERT INTO #temp
SELECT 1 ID, NULL AS ParentID
UNION ALL
SELECT 2, 1
UNION ALL
SELECT 3, 2
UNION ALL
SELECT 4, 3
UNION ALL
SELECT 5, 4
UNION ALL
SELECT 6, NULL
UNION ALL
SELECT 7, 6
UNION ALL
SELECT 8, 7
DECLARE #startNode INT = 4
;WITH TheTree (ID,ParentID)
AS (
SELECT ID, ParentID
FROM #temp
WHERE ID = #startNode
UNION ALL
SELECT t.id, t.ParentID
FROM #temp t
JOIN TheTree tr ON t.ParentID = tr.ID
)
SELECT * FROM TheTree
;WITH Up(ID,ParentID)
AS (
SELECT t.id, t.ParentID
FROM #temp t
WHERE t.ID = #startNode
UNION ALL
SELECT t.id, t.ParentID
FROM #temp t
JOIN Up c ON t.id = c.ParentID
)
--SELECT * FROM Up
,TheTree (ID,ParentID)
AS (
SELECT ID, ParentID
FROM Up
WHERE ParentID is null
UNION ALL
SELECT t.id, t.ParentID
FROM #temp t
JOIN TheTree tr ON t.ParentID = tr.ID
)
SELECT * FROM TheTree
thanks
Meh. This avoids using two CTEs, but the result is a brute force kludge that hardly qualifies as "sleek" as it won’t be efficient if your table is at all sizeable. It will:
Recursively build all possible hierarchies
As you build them, flag the target NodeId as you find it
Return only the targeted tree
I threw in column “TreeNumber” on the off-chance the TargetId appears in multiple hierarchies, or if you’d ever have multiple values to check in one pass. “Depth” was added to make the output a bit more legible.
A more complex solution like #John’s might do, and more and subtler tricks could be done with more detailed table sturctures.
DECLARE #startNode INT = 4
;WITH cteAllTrees (TreeNumber, Depth, ID, ParentID, ContainsTarget)
AS (
SELECT
row_number() over (order by ID) TreeNumber
,1
,ID
,ParentID
,case
when ID = #startNode then 1
else 0
end ContainsTarget
FROM #temp
WHERE ParentId is null
UNION ALL
SELECT
tr.TreeNumber
,tr.Depth + 1
,t.id
,t.ParentID
,case
when tr.ContainsTarget = 1 then 1
when t.ID = #startNode then 1
else 0
end ContainsTarget
FROM #temp t
INNER JOIN cteAllTrees tr
ON t.ParentID = tr.ID
)
SELECT
TreeNumber
,Depth
,ID
,ParentId
from cteAllTrees
where TreeNumber in (select TreeNumber from cteAllTrees where ContainsTarget = 1)
order by
TreeNumber
,Depth
,ID
Here is a technique where you can select the entire hierarchy, a specific node with all its children, and even a filtered list and how they roll.
Note: See the comments next to the DECLAREs
Declare #YourTable table (id int,pt int,name varchar(50))
Insert into #YourTable values
(1,null,'1'),(2,1,'2'),(3,1,'3'),(4,2,'4'),(5,2,'5'),(6,3,'6'),(7,null,'7'),(8,7,'8')
Declare #Top int = null --<< Sets top of Hier Try 2
Declare #Nest varchar(25) = '|-----' --<< Optional: Added for readability
Declare #Filter varchar(25) = '' --<< Empty for All or try 4,6
;with cteP as (
Select Seq = cast(1000+Row_Number() over (Order by name) as varchar(500))
,ID
,pt
,Lvl=1
,name
From #YourTable
Where IsNull(#Top,-1) = case when #Top is null then isnull(pt,-1) else ID end
Union All
Select Seq = cast(concat(p.Seq,'.',1000+Row_Number() over (Order by r.name)) as varchar(500))
,r.ID
,r.pt
,p.Lvl+1
,r.name
From #YourTable r
Join cteP p on r.pt = p.ID)
,cteR1 as (Select *,R1=Row_Number() over (Order By Seq) From cteP)
,cteR2 as (Select A.Seq,A.ID,R2=Max(B.R1) From cteR1 A Join cteR1 B on (B.Seq like A.Seq+'%') Group By A.Seq,A.ID )
Select Distinct
A.R1
,B.R2
,A.ID
,A.pt
,A.Lvl
,name = Replicate(#Nest,A.Lvl-1) + A.name
From cteR1 A
Join cteR2 B on A.ID=B.ID
Join (Select R1 From cteR1 where IIF(#Filter='',1,0)+CharIndex(concat(',',ID,','),concat(',',#Filter+','))>0) F on F.R1 between A.R1 and B.R2
Order By A.R1

postgres hierarchy - count of child levels and sort by date of children or grandchildren

I would like to know how to write a postgres subquery so that the following table example will output what I need.
id parent_id postdate
1   -1 2015-03-10
2     1 2015-03-11 (child level 1)
3     1 2015-03-12 (child level 1)
4     3 2015-03-13 (child level 2)
5    -1 2015-03-14
6    -1 2015-03-15
7     6 2015-03-16 (child level 1)
If I want to sort all the root ids by child level 1 with a count of children(s) from the parent, the output would be something like this
id count  date
6   2    2015-03-15
1   4    2015-03-10
5   1    2015-03-14
The output is sorted by postdate based on the root's child. The 'date' being outputted is the date of the root's postdate. Even though id#5 has a more recent postdate, the rootid#6's child (id#7) has the most recent postdate because it is being sorted by child's postdate. id#5 doesnt have any children so it just gets placed at the end, sorted by date. The 'count' is the number children(child level 1), grandchildren(child level 2) and itself (root). For instance, id #2,#3,#4 all belong to id#1 so for id#1, the count would be 4.
My current subquery thus far:
SELECT p1.id,count(p1.id),p1.postdate
FROM mytable p1
LEFT JOIN mytable c1 ON c1.parent_id = p1.id AND p1.parent_id = -1
LEFT JOIN mytable c2 ON c2.parent_id = c1.id AND p1.parent_id = -1
GROUP BY p1.id,c1.postdate,p1.postdate
ORDER by c1.postdate DESC,p1.postdate DESC
create table mytable ( id serial primary key, parent_id int references mytable, postdate date );
create index mytable_parent_id_idx on mytable (parent_id);
insert into mytable (id, parent_id, postdate) values (1, null, '2015-03-10');
insert into mytable (id, parent_id, postdate) values (2, 1, '2015-03-11');
insert into mytable (id, parent_id, postdate) values (3, 1, '2015-03-12');
insert into mytable (id, parent_id, postdate) values (4, 3, '2015-03-13');
insert into mytable (id, parent_id, postdate) values (5, null, '2015-03-14');
insert into mytable (id, parent_id, postdate) values (6, null, '2015-03-15');
insert into mytable (id, parent_id, postdate) values (7, 6, '2015-03-16');
with recursive recu as (
select id as parent, id as root, null::date as child_postdate
from mytable
where parent_id is null
union all
select r.parent, mytable.id, mytable.postdate
from recu r
join mytable
on parent_id = r.root
)
select m.id, c.cnt, m.postdate, c.max_child_date
from mytable m
join ( select parent, count(*) as cnt, max(child_postdate) as max_child_date
from recu
group by parent
) c on c.parent = m.id
order by c.max_child_date desc nulls last, m.postdate desc;
You'll need a recursive query to count the elements in the subtrees:
WITH RECURSIVE opa AS (
SELECT id AS par
, id AS moi
FROM the_tree
WHERE parent_id IS NULL
UNION ALL
SELECT o.par AS par
, t.id AS moi
FROM opa o
JOIN the_tree t ON t.parent_id = o.moi
)
SELECT t.id
, c.cnt
, t.postdate
FROM the_tree t
JOIN ( SELECT par, COUNT(*) AS cnt
FROM opa o
GROUP BY par
) c ON c.par = t.id
ORDER BY t.id
;
UPDATE (it appears the OP also wants the maxdate per tree)
-- The same, but also select the postdate
-- --------------------------------------
WITH RECURSIVE opa AS (
SELECT id AS par
, id AS moi
, postdate AS postdate
FROM the_tree
WHERE parent_id IS NULL
UNION ALL
SELECT o.par AS par
, t.id AS moi
-- , GREATEST(o.postdate,t.postdate) AS postdate
, t.postdate AS postdate
FROM opa o
JOIN the_tree t ON t.parent_id = o.moi
)
SELECT t.id
, c.cnt
, t.postdate
, c.maxdate
FROM the_tree t
JOIN ( SELECT par, COUNT(*) AS cnt
, MAX(o.postdate) AS maxdate -- and obtain the max()
FROM opa o
GROUP BY par
) c ON c.par = t.id
ORDER BY c.maxdate, t.id
;
After looking at everyone's code, I created the subquery I needed. I can use PHP to vary the 'case when' code depending on the user's sort selection. For instance, the code below will sort the root nodes based on child level 1's postdate.
with recursive cte as (
select id as parent, id as root, null::timestamp as child_postdate,0 as depth
from mytable
where parent_id = -1
union all
select r.parent, mytable.id, mytable.postdate,depth+1
from cte r
join mytable
on parent_id = r.root
)
select m.id, c.cnt, m.postdate
from ssf.dtb_021 m
join ( select parent, count(*) as cnt, max(child_postdate) as max_child_date,depth
from cte
group by parent,depth
) c on c.parent = m.id
order by
case
when depth=2 then 1
when depth=1 then 2
else 0
end DESC,
c.max_child_date desc nulls last, m.postdate desc;
select
p.id,
(1+c.n) as parent_post_plus_number_of_subposts,
p.postdate
from
table as p
inner join
(
select
parent_id, count(*) as n, max(postdate) as _postdate
from table
group by parent_id
) as c
on p.id = c.parent_id
where p.parent_id = -1
order by c._postdate desc

Can I Choose Different Table for inner join operation?

This is my T-SQL
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
inner join [tableA or tableB] on xxxxxxxx
I want join tableA when Profile = Soft and join tableB when Profile = Hard, how can I do just only using T-SQL in one batch?
Thanks
You can't directly do it, but could achieve the same effect with outer joins
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
left outer join tableA ON tableA.x = p1.x AND p1.Profile = 'Soft'
left outer join tableB ON tableB.x = p1.x AND p1.Profile = 'Hard'
where
where
(tableA.x IS NOT NULL and p1.Profile = 'Soft')
or (tableB.x IS NOT NULL and p1.Profile = 'Hard')
Of course, you can choose different tables for inner join operation, but it must be based on some condition or variable.
For Example:
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
inner join tableA A
on Profile='Soft'
AND <any other Condition>
UNION
select Id,Profile,Type ,
case Profile
when 'Soft' then 'SID'
when 'Hard' then 'HID'
end as [Profile]
from ProductDetail p1
inner join tableB B
on Profile='Hard'
AND <any other Condition>
You can do this in a single statement with the same or similar case statement in your join. Below is sample code using temp tables that joins to 2 different reference tables merged into a single result set using a UNION
DECLARE #ProductDetail TABLE (Id INT, sProfile VARCHAR(100), StID INT, HdID INT)
DECLARE #TableA TABLE (StId INT, Field1 VARCHAR(100))
DECLARE #TableB TABLE (HdId INT, Field1 VARCHAR(100))
INSERT INTO #ProductDetail (Id, sProfile, StID , HdID ) VALUES (1,'Soft',1,1)
INSERT INTO #ProductDetail (Id, sProfile, StID , HdID ) VALUES (2,'Hard',2,2)
INSERT INTO #TableA (StId,Field1) VALUES (1,'Soft 1')
INSERT INTO #TableA (StId,Field1) VALUES (2,'Soft 2')
INSERT INTO #TableB (HdId,Field1) VALUES (1,'Hard 1')
INSERT INTO #TableB (HdId,Field1) VALUES (2,'Hard 2')
SELECT
p1.Id,p1.sProfile,
CASE
WHEN p1.sProfile = 'Soft' THEN StID
WHEN p1.sProfile = 'Hard' THEN HdId
END AS [Profile]
,ReferenceTable.FieldName
FROM
#ProductDetail p1
INNER JOIN
(
SELECT StID AS id, 'Soft' AS sProfile, Field1 AS FieldName
FROM #TableA AS tableA
UNION ALL
SELECT HdID AS id, 'Hard' AS sProfile, Field1 AS FieldName
FROM #TableB AS tableB
)
AS ReferenceTable
ON
CASE
WHEN p1.sProfile = 'Soft' THEN StID
WHEN p1.sProfile = 'Hard' THEN HdID
END = ReferenceTable.Id
AND p1.sProfile = ReferenceTable.sProfile
This will return the following result set:
Id sProfile Profile FieldName
1 Soft 1 Soft 1
2 Hard 2 Hard 2

How to set the “Order” of Items in a hierarchy table in an easier and shorter way?

Refering to this post, here is the overall question and codes:
declare #tbl table (MenuItemID uniqueidentifier, PID uniqueidentifier, MenuID uniqueidentifier, SO tinyint, lvl tinyint)
;WITH
cte (MenuItemID, PID, MenuID, SO, lvl) AS
(
select MenuItemID, PID, MenuID, SO, 0 from MenuItems
where del = 0 and Perms = 1 and MenuID = #MenuID and MenuID = PID
UNION ALL
SELECT MenuItems.MenuItemID, MenuItems.PID, MenuItems.MenuID, MenuItems.SO, cte.lvl + 1 FROM MenuItems
JOIN cte ON cte.MenuItemID = MenuItems.PID
)
select * from cte
ORDER BY lvl, SO
insert into #tbl select * from cte
declare #tbl2 table (MenuItemID uniqueidentifier, PID uniqueidentifier, MenuID uniqueidentifier, SO tinyint, lvl tinyint)
;with hier (MenuItemID, PID, MenuID, SO, lvl, FullSO) as
(select l0.*, convert(varchar(max),right('000'+convert(varchar(3),SO),3)) FullSO
from #tbl l0 where lvl=0
union all
select ln.*, lp.FullSO+','+right('000'+convert(varchar(3),ln.SO),3) FullSO
from #tbl ln
join hier lp on ln.PID = lp.MenuItemID)
insert into #tbl2
select MenuItemID,
PID,
MenuID,
rank() over (partition by PID order by SO) SO,
lvl
from hier
order by FullSO, SO
update MenuItems set SO = h.SO
from MenuItems as mi
join #tbl2 h on mi.MenuItemID = h.MenuItemID and mi.MenuID = h.MenuID
I'd like to know whether there is an easier and shorter way for this code?
Thanks in advance,
Kardo
You will still need a recursive CTE to determine which top-level records for the hierarchy have del = 0 and Perms = 1, but the following should be simpler:
WITH cte AS
(select MenuItemID, PID, MenuID, SO,
rank() over (partition by PID order by SO) newSO
from MenuItems
where del = 0 and Perms = 1 and MenuID = #MenuID and MenuID = PID
UNION ALL
SELECT m.MenuItemID, m.PID, m.MenuID, m.SO,
rank() over (partition by m.PID order by m.SO) newSO
FROM MenuItems m
JOIN cte c ON c.MenuItemID = m.PID
)
update MenuItems set SO = h.newSO
from MenuItems as mi
join cte h on mi.MenuItemID = h.MenuItemID and mi.MenuID = h.MenuID;
SQLFiddle here.