Search
 
SCRIPT & CODE EXAMPLE
 

SQL

how to find all children of a record with only parent ID in sql

DECLARE @Table TABLE(
        ID INT,
        ParentID INT,
        NAME VARCHAR(20)
)

INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 1, NULL, 'A'
INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 2, 1, 'B-1'
INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 3, 1, 'B-2'
INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 4, 2, 'C-1'
INSERT INTO @Table (ID,ParentID,[NAME]) SELECT 5, 2, 'C-2'


DECLARE @ID INT

SELECT @ID = 2

;WITH ret AS(
        SELECT  *
        FROM    @Table
        WHERE   ID = @ID
        UNION ALL
        SELECT  t.*
        FROM    @Table t INNER JOIN
                ret r ON t.ParentID = r.ID
)

SELECT  *
FROM    ret
Comment

sql - Find all children who are not parent

WHERE ID NOT IN (SELECT ParentID FROM [SMD].[dbo].[ProposalFollowUp])
Comment

sql - Find all children who are not parent

SELECT ID, ParentID 
FROM [SMD].[dbo].[ProposalFollowUp] t1
WHERE NOT EXISTS
(
   SELECT 1 FROM [SMD].[dbo].[ProposalFollowUp] t2
   WHERE t2.ParentID = t1.ID
)
Comment

PREVIOUS NEXT
Code Example
Sql :: view table mysql 
Sql :: if mysql 
Sql :: run sql script from command line 
Sql :: how to select random rows from a table 
Sql :: open postgresql.conf 
Sql :: duplicate key value violates unique constraint in postgresql 
Sql :: ms sql database data size 
Sql :: sql find second highest salary employee 
Sql :: INITCAP in Oracle example 
Sql :: create table like another table 
Sql :: how to upper case in sql 
Sql :: laravel eloquent get generated sql 
Sql :: mysql regex exact match 
Sql :: null column as zero in mysql 
Sql :: select users with same username 
Sql :: create empty table from existing table 
Sql :: multiple count with where clause sql 
Sql :: sql ending with vowels 
Sql :: mssql server port 
Sql :: timestamp difference sql 
Sql :: sql server today minus n 
Sql :: postgresql concat string with separator 
Sql :: difference between 2 query results sql server 
Sql :: truncate table sqlite 
Sql :: import mysql database command line 
Sql :: sql statement to change a field value 
Sql :: how to create a table based on another table in mysql 
Sql :: install mysql in ubuntu 18.04 
Sql :: r write csv without index 
Sql :: sql like case sensitive 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =