Thursday, 21 November 2013

Example of using Left join,Self join and union all.



CREATE TABLE [dbo].[Folder] (
    [FolderID]         INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
    [FolderName]       VARCHAR(100) NOT NULL,
    [ParentFolderID]   INT NULL REFERENCES [dbo].[Folder]( [FolderID] ) 
) 

CREATE TABLE [dbo].[File] (
    [FileID]           INT NOT NULL PRIMARY KEY IDENTITY(1, 1),
    [FolderID]         INT NOT NULL REFERENCES [dbo].[Folder] ( [FolderID] ),
    [FileName]         VARCHAR(100)
)

INSERT INTO [dbo].[Folder] ( [FolderName] )
VALUES ( 'Inetpub' )

INSERT INTO [dbo].[Folder] ( [FolderName] )
VALUES ( 'Program Files' )

INSERT INTO [dbo].[Folder] ( [FolderName] )
VALUES ( 'Windows' )

INSERT INTO [dbo].[Folder] ( [FolderName], [ParentFolderID] )
VALUES ( 'wwwroot', 1 )

INSERT INTO [dbo].[Folder] ( [FolderName], [ParentFolderID] )
VALUES ( 'Microsoft Office', 2 )

INSERT INTO [dbo].[Folder] ( [FolderName], [ParentFolderID] )
VALUES ( 'Microsoft SQL Server', 2 )

INSERT INTO [dbo].[Folder] ( [FolderName], [ParentFolderID] )
VALUES ( 'assembly', 3 )

INSERT INTO [dbo].[Folder] ( [FolderName], [ParentFolderID] )
VALUES ( 'system32', 3 ) 

INSERT INTO [dbo].[File] ( [FolderID], [FileName] )
VALUES ( 4, 'iisstart.htm')

INSERT INTO [dbo].[File] ( [FolderID], [FileName] )
VALUES ( 8, 'calc.exe')

INSERT INTO [dbo].[File] ( [FolderID], [FileName] )
VALUES ( 8, 'notepad.exe')
 and the reuslt is shown in the image,
If nulls in the parentid means separate and left join with the file table to get file names with the folder names,
select A.FolderID FolderID,'/'+A.FolderName FolderName,'' as ParentFolder,B.FileName FileName from Folder A
left join [File] B
on A.FolderID=B.FolderID
where A.ParentFolderID is null
And separate non null parentid and join with folder table                                      select m.FolderID,'/'+m.FolderName FolderName,'/'+t.FolderName+'/'+m.FolderName as p,m.FileName from Folder t
join (
select A.FolderID FolderID,A.FolderName FolderName,A.ParentFolderID as ParentFolder,B.FileName FileName from Folder A
left join [File] B
on A.FolderID=B.FolderID
where A.ParentFolderID is not null)m
on t.FolderID=m.ParentFolder
and union all both queries to get desired results 
select A.FolderID FolderID,'/'+A.FolderName FolderName,'' as ParentFolder,B.FileName FileName from Folder A
left join [File] B
on A.FolderID=B.FolderID
where A.ParentFolderID is null

union all

select m.FolderID,'/'+m.FolderName FolderName,'/'+t.FolderName+'/'+m.FolderName as p,m.FileName from Folder t
join (
select A.FolderID FolderID,A.FolderName FolderName,A.ParentFolderID as ParentFolder,B.FileName FileName from Folder A
left join [File] B
on A.FolderID=B.FolderID
where A.ParentFolderID is not null)m
on t.FolderID=m.ParentFolder

No comments:

Post a Comment