Generate permutations and combination for name columnPermutation and Combination of wordsSQL Server 2008 datetime index performance bugDoes SQL Server check disk space before allocating a new page?Oracle GoldenGate add trandata errorsImprove query performance when selecting almost all rows with many “group by” columnsColumn Name in separate table SQL ServerReplication and AlwaysOn combinationInvalid column name 'database_id'Investigating errors from strange queryGroup by sum based on under group in SQL Serverselect single row from table for a particular column combination

Why does my circuit work on a breadboard, but not on a perfboard? I am new to soldering

On studying Computer Science vs. Software Engineering to become a proficient coder

Drawing lines to nearest point

What food production methods would allow a metropolis like New York to become self sufficient

Word for being out at night during curfew

What does the expression "right on the tip of my tongue" mean?

How did Thanos not realise this had happened at the end of Endgame?

Can I use my laptop, which says 100-240V, in the USA?

Extrude the faces of a cube symmetrically along XYZ

Why in a Ethernet LAN, a packet sniffer can obtain all packets sent over the LAN?

Early arrival in Australia, early hotel check in not available

Create a list of all possible Boolean configurations of three constraints

Size of a folder with du

How do I tell my supervisor that he is choosing poor replacements for me while I am on maternity leave?

Is there ever any indication in the MCU as to how Spider-Man got his powers?

SSD - Disk is OK, one bad sector

Meaning of「〜てみたいと思います」

Reaction of borax with NaOH

Does Lawful Interception of 4G / the proposed 5G provide a back door for hackers as well?

Why is “Ich wusste, dass aus dir mal was wird” grammitally correct?

Surely they can fit?

What is the relation between semi-supervised self-supervised visual representation learning?

Why does the Earth follow an elliptical trajectory rather than a parabolic one?

Do atomic orbitals "pulse" in time?



Generate permutations and combination for name column


Permutation and Combination of wordsSQL Server 2008 datetime index performance bugDoes SQL Server check disk space before allocating a new page?Oracle GoldenGate add trandata errorsImprove query performance when selecting almost all rows with many “group by” columnsColumn Name in separate table SQL ServerReplication and AlwaysOn combinationInvalid column name 'database_id'Investigating errors from strange queryGroup by sum based on under group in SQL Serverselect single row from table for a particular column combination






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








8















I have the following sample data for permutations and combination.



create table tbltest
(
name varchar(50),
addres varchar(100)
);

insert into tbltest values('Sam Mak John','Street 1 HNo 101 USA');
insert into tbltest values('Donatella Nobatti','HNo 101 UK');
insert into tbltest values('Sam Buca','Main Road B Block UAE');
insert into tbltest values('Juan Soponatime','Hight Street CA');
insert into tbltest values('Aaron Spacemuseum','HNo A10 100 feet Road A Block ');


I want to generate permutations and combinations for the name column in the table tbltest and store into temp table.



For an example expected result:



name
----------------
John Mak Sam
John Sam Mak
Mak John Sam
Mak Sam John
Sam John Mak
Sam Mak John
....
....


Tried with following query: Source



Note: Following query works as expected for single record but when I tried on table using cursor its running more than 35 min and still keeps running.



DECLARE @inputStr VARCHAR(MAX)= 'Sam Mak John';
DECLARE @ValueStr VARCHAR(100);
DECLARE @Count INT, @Loop INT= 1, @totalSum INT;
DECLARE @Query1 VARCHAR(1000), @Query2 VARCHAR(1000), @Query3 VARCHAR(1000), @Query4 VARCHAR(1000), @Query5 VARCHAR(1000), @Query6 VARCHAR(1000), @Query VARCHAR(4000), @Combination VARCHAR(1000);

--Temporary table to capture all the words separately
CREATE TABLE #tmpvalues
(intIndex INT IDENTITY(1, 1),
intProc INT,
subStr VARCHAR(100)
);

--Temporary table to store all the possible combinations
CREATE TABLE #tmpCombinations
(subCombStr VARCHAR(1000)
);

--get the sub-strings(words) from input statement into a temp table
WHILE LEN(@inputStr) > 0
BEGIN
SET @ValueStr = LEFT(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr) - 1, -1), LEN(@inputStr)));
SET @inputStr = SUBSTRING(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr), 0), LEN(@inputStr)) + 1, LEN(@inputStr));
INSERT INTO #tmpvalues
VALUES
(@Loop,
@ValueStr
);
SET @Loop = @Loop + 1;
END;
SELECT @Count = MAX(intINDEX)
FROM #tmpvalues;
SET @Loop = 1;

--Set an integer values for each words
--This will be used to filter the combinations in which any two words are repating
DECLARE @tempIntAdd INT;--Addition factor
SET @tempIntAdd = @Loop * @Count;
WHILE @Loop <= (@Count - 1)
BEGIN
DECLARE @tempIntProc INT;
SELECT @tempIntProc = intProc
FROM #tmpvalues
WHERE intIndex = @Loop;
UPDATE #tmpvalues
SET
intProc = @tempIntProc + @tempIntAdd
WHERE intIndex = @Loop + 1;
SET @Loop = @Loop + 1;
SET @tempIntAdd = @tempIntAdd * 2;
END;
--
SET @Loop = 1;
SET @Query1 = 'INSERT INTO #tmpCombinations SELECT DISTINCT ';
SET @Query2 = 'ALL_COMBINATIONS FROM';
SET @Query3 = ' ';
SET @Query4 = ' WHERE';
SET @Query5 = '(';
SET @Query6 = ')';

-- Generate the dynamic query to get permutations and combination of individual words
WHILE @Loop <= @Count
BEGIN
SELECT @ValueStr = subStr
FROM #tmpvalues
WHERE intIndex = @Loop;
SET @Query1 = @Query1 + 'T' + CAST(@Loop AS VARCHAR) + '.subStr ';
IF(@Loop < @Count)
SET @Query1 = @Query1 + '+ '' '' + ';
SET @Query3 = @Query3 + '#tmpvalues ' + 'T' + CAST(@Loop AS VARCHAR);
IF(@Loop < @Count)
SET @Query3 = @Query3 + ', ';
SET @Query5 = @Query5 + 'T' + CAST(@Loop AS VARCHAR) + '.intProc';
IF(@Loop < @Count)
SET @Query5 = @Query5 + ' + ';
SET @Loop = @Loop + 1;
END;
SELECT @totalSum = SUM(intProc)
FROM #tmpvalues;

--Create final query
SET @Query = @Query1 + @Query2 + @Query3 + @Query4 + @Query5 + @Query6 + ' =' + CAST(@totalSum AS VARCHAR);

--Execute the dynamic Query
EXECUTE (@Query);

SELECT subCombStr from #tmpCombinations









share|improve this question






















  • So just to be clear, you want to take the name column, split it by the space character into rows, and then get every possible combination of names between those rows?

    – George.Palacios
    May 8 at 7:51











  • @George.Palacios, Yes exactly.

    – MAK
    May 8 at 7:53











  • Should they all be 3 names long? Or do you want every possible combination?

    – George.Palacios
    May 8 at 7:59











  • @George.Palacios, They may comes with any numbers of words.

    – MAK
    May 8 at 8:02

















8















I have the following sample data for permutations and combination.



create table tbltest
(
name varchar(50),
addres varchar(100)
);

insert into tbltest values('Sam Mak John','Street 1 HNo 101 USA');
insert into tbltest values('Donatella Nobatti','HNo 101 UK');
insert into tbltest values('Sam Buca','Main Road B Block UAE');
insert into tbltest values('Juan Soponatime','Hight Street CA');
insert into tbltest values('Aaron Spacemuseum','HNo A10 100 feet Road A Block ');


I want to generate permutations and combinations for the name column in the table tbltest and store into temp table.



For an example expected result:



name
----------------
John Mak Sam
John Sam Mak
Mak John Sam
Mak Sam John
Sam John Mak
Sam Mak John
....
....


Tried with following query: Source



Note: Following query works as expected for single record but when I tried on table using cursor its running more than 35 min and still keeps running.



DECLARE @inputStr VARCHAR(MAX)= 'Sam Mak John';
DECLARE @ValueStr VARCHAR(100);
DECLARE @Count INT, @Loop INT= 1, @totalSum INT;
DECLARE @Query1 VARCHAR(1000), @Query2 VARCHAR(1000), @Query3 VARCHAR(1000), @Query4 VARCHAR(1000), @Query5 VARCHAR(1000), @Query6 VARCHAR(1000), @Query VARCHAR(4000), @Combination VARCHAR(1000);

--Temporary table to capture all the words separately
CREATE TABLE #tmpvalues
(intIndex INT IDENTITY(1, 1),
intProc INT,
subStr VARCHAR(100)
);

--Temporary table to store all the possible combinations
CREATE TABLE #tmpCombinations
(subCombStr VARCHAR(1000)
);

--get the sub-strings(words) from input statement into a temp table
WHILE LEN(@inputStr) > 0
BEGIN
SET @ValueStr = LEFT(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr) - 1, -1), LEN(@inputStr)));
SET @inputStr = SUBSTRING(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr), 0), LEN(@inputStr)) + 1, LEN(@inputStr));
INSERT INTO #tmpvalues
VALUES
(@Loop,
@ValueStr
);
SET @Loop = @Loop + 1;
END;
SELECT @Count = MAX(intINDEX)
FROM #tmpvalues;
SET @Loop = 1;

--Set an integer values for each words
--This will be used to filter the combinations in which any two words are repating
DECLARE @tempIntAdd INT;--Addition factor
SET @tempIntAdd = @Loop * @Count;
WHILE @Loop <= (@Count - 1)
BEGIN
DECLARE @tempIntProc INT;
SELECT @tempIntProc = intProc
FROM #tmpvalues
WHERE intIndex = @Loop;
UPDATE #tmpvalues
SET
intProc = @tempIntProc + @tempIntAdd
WHERE intIndex = @Loop + 1;
SET @Loop = @Loop + 1;
SET @tempIntAdd = @tempIntAdd * 2;
END;
--
SET @Loop = 1;
SET @Query1 = 'INSERT INTO #tmpCombinations SELECT DISTINCT ';
SET @Query2 = 'ALL_COMBINATIONS FROM';
SET @Query3 = ' ';
SET @Query4 = ' WHERE';
SET @Query5 = '(';
SET @Query6 = ')';

-- Generate the dynamic query to get permutations and combination of individual words
WHILE @Loop <= @Count
BEGIN
SELECT @ValueStr = subStr
FROM #tmpvalues
WHERE intIndex = @Loop;
SET @Query1 = @Query1 + 'T' + CAST(@Loop AS VARCHAR) + '.subStr ';
IF(@Loop < @Count)
SET @Query1 = @Query1 + '+ '' '' + ';
SET @Query3 = @Query3 + '#tmpvalues ' + 'T' + CAST(@Loop AS VARCHAR);
IF(@Loop < @Count)
SET @Query3 = @Query3 + ', ';
SET @Query5 = @Query5 + 'T' + CAST(@Loop AS VARCHAR) + '.intProc';
IF(@Loop < @Count)
SET @Query5 = @Query5 + ' + ';
SET @Loop = @Loop + 1;
END;
SELECT @totalSum = SUM(intProc)
FROM #tmpvalues;

--Create final query
SET @Query = @Query1 + @Query2 + @Query3 + @Query4 + @Query5 + @Query6 + ' =' + CAST(@totalSum AS VARCHAR);

--Execute the dynamic Query
EXECUTE (@Query);

SELECT subCombStr from #tmpCombinations









share|improve this question






















  • So just to be clear, you want to take the name column, split it by the space character into rows, and then get every possible combination of names between those rows?

    – George.Palacios
    May 8 at 7:51











  • @George.Palacios, Yes exactly.

    – MAK
    May 8 at 7:53











  • Should they all be 3 names long? Or do you want every possible combination?

    – George.Palacios
    May 8 at 7:59











  • @George.Palacios, They may comes with any numbers of words.

    – MAK
    May 8 at 8:02













8












8








8


2






I have the following sample data for permutations and combination.



create table tbltest
(
name varchar(50),
addres varchar(100)
);

insert into tbltest values('Sam Mak John','Street 1 HNo 101 USA');
insert into tbltest values('Donatella Nobatti','HNo 101 UK');
insert into tbltest values('Sam Buca','Main Road B Block UAE');
insert into tbltest values('Juan Soponatime','Hight Street CA');
insert into tbltest values('Aaron Spacemuseum','HNo A10 100 feet Road A Block ');


I want to generate permutations and combinations for the name column in the table tbltest and store into temp table.



For an example expected result:



name
----------------
John Mak Sam
John Sam Mak
Mak John Sam
Mak Sam John
Sam John Mak
Sam Mak John
....
....


Tried with following query: Source



Note: Following query works as expected for single record but when I tried on table using cursor its running more than 35 min and still keeps running.



DECLARE @inputStr VARCHAR(MAX)= 'Sam Mak John';
DECLARE @ValueStr VARCHAR(100);
DECLARE @Count INT, @Loop INT= 1, @totalSum INT;
DECLARE @Query1 VARCHAR(1000), @Query2 VARCHAR(1000), @Query3 VARCHAR(1000), @Query4 VARCHAR(1000), @Query5 VARCHAR(1000), @Query6 VARCHAR(1000), @Query VARCHAR(4000), @Combination VARCHAR(1000);

--Temporary table to capture all the words separately
CREATE TABLE #tmpvalues
(intIndex INT IDENTITY(1, 1),
intProc INT,
subStr VARCHAR(100)
);

--Temporary table to store all the possible combinations
CREATE TABLE #tmpCombinations
(subCombStr VARCHAR(1000)
);

--get the sub-strings(words) from input statement into a temp table
WHILE LEN(@inputStr) > 0
BEGIN
SET @ValueStr = LEFT(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr) - 1, -1), LEN(@inputStr)));
SET @inputStr = SUBSTRING(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr), 0), LEN(@inputStr)) + 1, LEN(@inputStr));
INSERT INTO #tmpvalues
VALUES
(@Loop,
@ValueStr
);
SET @Loop = @Loop + 1;
END;
SELECT @Count = MAX(intINDEX)
FROM #tmpvalues;
SET @Loop = 1;

--Set an integer values for each words
--This will be used to filter the combinations in which any two words are repating
DECLARE @tempIntAdd INT;--Addition factor
SET @tempIntAdd = @Loop * @Count;
WHILE @Loop <= (@Count - 1)
BEGIN
DECLARE @tempIntProc INT;
SELECT @tempIntProc = intProc
FROM #tmpvalues
WHERE intIndex = @Loop;
UPDATE #tmpvalues
SET
intProc = @tempIntProc + @tempIntAdd
WHERE intIndex = @Loop + 1;
SET @Loop = @Loop + 1;
SET @tempIntAdd = @tempIntAdd * 2;
END;
--
SET @Loop = 1;
SET @Query1 = 'INSERT INTO #tmpCombinations SELECT DISTINCT ';
SET @Query2 = 'ALL_COMBINATIONS FROM';
SET @Query3 = ' ';
SET @Query4 = ' WHERE';
SET @Query5 = '(';
SET @Query6 = ')';

-- Generate the dynamic query to get permutations and combination of individual words
WHILE @Loop <= @Count
BEGIN
SELECT @ValueStr = subStr
FROM #tmpvalues
WHERE intIndex = @Loop;
SET @Query1 = @Query1 + 'T' + CAST(@Loop AS VARCHAR) + '.subStr ';
IF(@Loop < @Count)
SET @Query1 = @Query1 + '+ '' '' + ';
SET @Query3 = @Query3 + '#tmpvalues ' + 'T' + CAST(@Loop AS VARCHAR);
IF(@Loop < @Count)
SET @Query3 = @Query3 + ', ';
SET @Query5 = @Query5 + 'T' + CAST(@Loop AS VARCHAR) + '.intProc';
IF(@Loop < @Count)
SET @Query5 = @Query5 + ' + ';
SET @Loop = @Loop + 1;
END;
SELECT @totalSum = SUM(intProc)
FROM #tmpvalues;

--Create final query
SET @Query = @Query1 + @Query2 + @Query3 + @Query4 + @Query5 + @Query6 + ' =' + CAST(@totalSum AS VARCHAR);

--Execute the dynamic Query
EXECUTE (@Query);

SELECT subCombStr from #tmpCombinations









share|improve this question














I have the following sample data for permutations and combination.



create table tbltest
(
name varchar(50),
addres varchar(100)
);

insert into tbltest values('Sam Mak John','Street 1 HNo 101 USA');
insert into tbltest values('Donatella Nobatti','HNo 101 UK');
insert into tbltest values('Sam Buca','Main Road B Block UAE');
insert into tbltest values('Juan Soponatime','Hight Street CA');
insert into tbltest values('Aaron Spacemuseum','HNo A10 100 feet Road A Block ');


I want to generate permutations and combinations for the name column in the table tbltest and store into temp table.



For an example expected result:



name
----------------
John Mak Sam
John Sam Mak
Mak John Sam
Mak Sam John
Sam John Mak
Sam Mak John
....
....


Tried with following query: Source



Note: Following query works as expected for single record but when I tried on table using cursor its running more than 35 min and still keeps running.



DECLARE @inputStr VARCHAR(MAX)= 'Sam Mak John';
DECLARE @ValueStr VARCHAR(100);
DECLARE @Count INT, @Loop INT= 1, @totalSum INT;
DECLARE @Query1 VARCHAR(1000), @Query2 VARCHAR(1000), @Query3 VARCHAR(1000), @Query4 VARCHAR(1000), @Query5 VARCHAR(1000), @Query6 VARCHAR(1000), @Query VARCHAR(4000), @Combination VARCHAR(1000);

--Temporary table to capture all the words separately
CREATE TABLE #tmpvalues
(intIndex INT IDENTITY(1, 1),
intProc INT,
subStr VARCHAR(100)
);

--Temporary table to store all the possible combinations
CREATE TABLE #tmpCombinations
(subCombStr VARCHAR(1000)
);

--get the sub-strings(words) from input statement into a temp table
WHILE LEN(@inputStr) > 0
BEGIN
SET @ValueStr = LEFT(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr) - 1, -1), LEN(@inputStr)));
SET @inputStr = SUBSTRING(@inputStr, ISNULL(NULLIF(CHARINDEX(' ', @inputStr), 0), LEN(@inputStr)) + 1, LEN(@inputStr));
INSERT INTO #tmpvalues
VALUES
(@Loop,
@ValueStr
);
SET @Loop = @Loop + 1;
END;
SELECT @Count = MAX(intINDEX)
FROM #tmpvalues;
SET @Loop = 1;

--Set an integer values for each words
--This will be used to filter the combinations in which any two words are repating
DECLARE @tempIntAdd INT;--Addition factor
SET @tempIntAdd = @Loop * @Count;
WHILE @Loop <= (@Count - 1)
BEGIN
DECLARE @tempIntProc INT;
SELECT @tempIntProc = intProc
FROM #tmpvalues
WHERE intIndex = @Loop;
UPDATE #tmpvalues
SET
intProc = @tempIntProc + @tempIntAdd
WHERE intIndex = @Loop + 1;
SET @Loop = @Loop + 1;
SET @tempIntAdd = @tempIntAdd * 2;
END;
--
SET @Loop = 1;
SET @Query1 = 'INSERT INTO #tmpCombinations SELECT DISTINCT ';
SET @Query2 = 'ALL_COMBINATIONS FROM';
SET @Query3 = ' ';
SET @Query4 = ' WHERE';
SET @Query5 = '(';
SET @Query6 = ')';

-- Generate the dynamic query to get permutations and combination of individual words
WHILE @Loop <= @Count
BEGIN
SELECT @ValueStr = subStr
FROM #tmpvalues
WHERE intIndex = @Loop;
SET @Query1 = @Query1 + 'T' + CAST(@Loop AS VARCHAR) + '.subStr ';
IF(@Loop < @Count)
SET @Query1 = @Query1 + '+ '' '' + ';
SET @Query3 = @Query3 + '#tmpvalues ' + 'T' + CAST(@Loop AS VARCHAR);
IF(@Loop < @Count)
SET @Query3 = @Query3 + ', ';
SET @Query5 = @Query5 + 'T' + CAST(@Loop AS VARCHAR) + '.intProc';
IF(@Loop < @Count)
SET @Query5 = @Query5 + ' + ';
SET @Loop = @Loop + 1;
END;
SELECT @totalSum = SUM(intProc)
FROM #tmpvalues;

--Create final query
SET @Query = @Query1 + @Query2 + @Query3 + @Query4 + @Query5 + @Query6 + ' =' + CAST(@totalSum AS VARCHAR);

--Execute the dynamic Query
EXECUTE (@Query);

SELECT subCombStr from #tmpCombinations






sql-server sql-server-2008-r2






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 8 at 7:49









MAKMAK

1684




1684












  • So just to be clear, you want to take the name column, split it by the space character into rows, and then get every possible combination of names between those rows?

    – George.Palacios
    May 8 at 7:51











  • @George.Palacios, Yes exactly.

    – MAK
    May 8 at 7:53











  • Should they all be 3 names long? Or do you want every possible combination?

    – George.Palacios
    May 8 at 7:59











  • @George.Palacios, They may comes with any numbers of words.

    – MAK
    May 8 at 8:02

















  • So just to be clear, you want to take the name column, split it by the space character into rows, and then get every possible combination of names between those rows?

    – George.Palacios
    May 8 at 7:51











  • @George.Palacios, Yes exactly.

    – MAK
    May 8 at 7:53











  • Should they all be 3 names long? Or do you want every possible combination?

    – George.Palacios
    May 8 at 7:59











  • @George.Palacios, They may comes with any numbers of words.

    – MAK
    May 8 at 8:02
















So just to be clear, you want to take the name column, split it by the space character into rows, and then get every possible combination of names between those rows?

– George.Palacios
May 8 at 7:51





So just to be clear, you want to take the name column, split it by the space character into rows, and then get every possible combination of names between those rows?

– George.Palacios
May 8 at 7:51













@George.Palacios, Yes exactly.

– MAK
May 8 at 7:53





@George.Palacios, Yes exactly.

– MAK
May 8 at 7:53













Should they all be 3 names long? Or do you want every possible combination?

– George.Palacios
May 8 at 7:59





Should they all be 3 names long? Or do you want every possible combination?

– George.Palacios
May 8 at 7:59













@George.Palacios, They may comes with any numbers of words.

– MAK
May 8 at 8:02





@George.Palacios, They may comes with any numbers of words.

– MAK
May 8 at 8:02










1 Answer
1






active

oldest

votes


















12














If you split each name into a separate table of the following structure,



CREATE TABLE dbo.NameParts
(
ID int NOT NULL,
NamePart varchar(30) NOT NULL
);


(where ID marks name parts that belong to the same name, to avoid permutation of parts of different names) – then you can use a recursive CTE to produce the permutations:



WITH
permutations AS
(
SELECT
ID = t.ID,
FullNameVariation = CAST(t.NamePart AS varchar(500)),
Level = COUNT(*) OVER (PARTITION BY t.ID)
FROM
dbo.NameParts AS t
UNION ALL
SELECT
ID = t.ID,
FullNameVariation = CAST(p.FullNameVariation + ' ' + t.NamePart AS varchar(500)),
Level = p.Level - 1
FROM
dbo.NameParts AS t
INNER JOIN permutations AS p ON t.ID = p.ID
WHERE 1=1
AND p.Level > 1
AND ' ' + p.FullNameVariation + ' ' NOT LIKE '% ' + t.NamePart + ' %'
)
SELECT
ID,
FullNameVariation
FROM
permutations
WHERE
Level = 1
ORDER BY
ID,
FullNameVariation
;


Applying the query to this data sample:



INSERT INTO dbo.NameParts
VALUES
(1, 'Sam'), (1, 'Mak'), (1, 'John'),
(2, 'Donatella'), (2, 'Nobatti'),
(3, 'Sam'), (3, 'Buca'),
(4, 'Juan'), (4, 'Soponatime'),
(5, 'Aaron'), (5, 'Spacemuseum')
;


produces the following output:



ID FullNameVariation
-- -----------------
1 John Mak Sam
1 John Sam Mak
1 Mak John Sam
1 Mak Sam John
1 Sam John Mak
1 Sam Mak John
2 Donatella Nobatti
2 Nobatti Donatella
3 Buca Sam
3 Sam Buca
4 Juan Soponatime
4 Soponatime Juan
5 Aaron Spacemuseum
5 Spacemuseum Aaron


You can play with this solution using a live demo at dbfiddle logodb<>fiddle.uk.






share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "182"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237619%2fgenerate-permutations-and-combination-for-name-column%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    12














    If you split each name into a separate table of the following structure,



    CREATE TABLE dbo.NameParts
    (
    ID int NOT NULL,
    NamePart varchar(30) NOT NULL
    );


    (where ID marks name parts that belong to the same name, to avoid permutation of parts of different names) – then you can use a recursive CTE to produce the permutations:



    WITH
    permutations AS
    (
    SELECT
    ID = t.ID,
    FullNameVariation = CAST(t.NamePart AS varchar(500)),
    Level = COUNT(*) OVER (PARTITION BY t.ID)
    FROM
    dbo.NameParts AS t
    UNION ALL
    SELECT
    ID = t.ID,
    FullNameVariation = CAST(p.FullNameVariation + ' ' + t.NamePart AS varchar(500)),
    Level = p.Level - 1
    FROM
    dbo.NameParts AS t
    INNER JOIN permutations AS p ON t.ID = p.ID
    WHERE 1=1
    AND p.Level > 1
    AND ' ' + p.FullNameVariation + ' ' NOT LIKE '% ' + t.NamePart + ' %'
    )
    SELECT
    ID,
    FullNameVariation
    FROM
    permutations
    WHERE
    Level = 1
    ORDER BY
    ID,
    FullNameVariation
    ;


    Applying the query to this data sample:



    INSERT INTO dbo.NameParts
    VALUES
    (1, 'Sam'), (1, 'Mak'), (1, 'John'),
    (2, 'Donatella'), (2, 'Nobatti'),
    (3, 'Sam'), (3, 'Buca'),
    (4, 'Juan'), (4, 'Soponatime'),
    (5, 'Aaron'), (5, 'Spacemuseum')
    ;


    produces the following output:



    ID FullNameVariation
    -- -----------------
    1 John Mak Sam
    1 John Sam Mak
    1 Mak John Sam
    1 Mak Sam John
    1 Sam John Mak
    1 Sam Mak John
    2 Donatella Nobatti
    2 Nobatti Donatella
    3 Buca Sam
    3 Sam Buca
    4 Juan Soponatime
    4 Soponatime Juan
    5 Aaron Spacemuseum
    5 Spacemuseum Aaron


    You can play with this solution using a live demo at dbfiddle logodb<>fiddle.uk.






    share|improve this answer





























      12














      If you split each name into a separate table of the following structure,



      CREATE TABLE dbo.NameParts
      (
      ID int NOT NULL,
      NamePart varchar(30) NOT NULL
      );


      (where ID marks name parts that belong to the same name, to avoid permutation of parts of different names) – then you can use a recursive CTE to produce the permutations:



      WITH
      permutations AS
      (
      SELECT
      ID = t.ID,
      FullNameVariation = CAST(t.NamePart AS varchar(500)),
      Level = COUNT(*) OVER (PARTITION BY t.ID)
      FROM
      dbo.NameParts AS t
      UNION ALL
      SELECT
      ID = t.ID,
      FullNameVariation = CAST(p.FullNameVariation + ' ' + t.NamePart AS varchar(500)),
      Level = p.Level - 1
      FROM
      dbo.NameParts AS t
      INNER JOIN permutations AS p ON t.ID = p.ID
      WHERE 1=1
      AND p.Level > 1
      AND ' ' + p.FullNameVariation + ' ' NOT LIKE '% ' + t.NamePart + ' %'
      )
      SELECT
      ID,
      FullNameVariation
      FROM
      permutations
      WHERE
      Level = 1
      ORDER BY
      ID,
      FullNameVariation
      ;


      Applying the query to this data sample:



      INSERT INTO dbo.NameParts
      VALUES
      (1, 'Sam'), (1, 'Mak'), (1, 'John'),
      (2, 'Donatella'), (2, 'Nobatti'),
      (3, 'Sam'), (3, 'Buca'),
      (4, 'Juan'), (4, 'Soponatime'),
      (5, 'Aaron'), (5, 'Spacemuseum')
      ;


      produces the following output:



      ID FullNameVariation
      -- -----------------
      1 John Mak Sam
      1 John Sam Mak
      1 Mak John Sam
      1 Mak Sam John
      1 Sam John Mak
      1 Sam Mak John
      2 Donatella Nobatti
      2 Nobatti Donatella
      3 Buca Sam
      3 Sam Buca
      4 Juan Soponatime
      4 Soponatime Juan
      5 Aaron Spacemuseum
      5 Spacemuseum Aaron


      You can play with this solution using a live demo at dbfiddle logodb<>fiddle.uk.






      share|improve this answer



























        12












        12








        12







        If you split each name into a separate table of the following structure,



        CREATE TABLE dbo.NameParts
        (
        ID int NOT NULL,
        NamePart varchar(30) NOT NULL
        );


        (where ID marks name parts that belong to the same name, to avoid permutation of parts of different names) – then you can use a recursive CTE to produce the permutations:



        WITH
        permutations AS
        (
        SELECT
        ID = t.ID,
        FullNameVariation = CAST(t.NamePart AS varchar(500)),
        Level = COUNT(*) OVER (PARTITION BY t.ID)
        FROM
        dbo.NameParts AS t
        UNION ALL
        SELECT
        ID = t.ID,
        FullNameVariation = CAST(p.FullNameVariation + ' ' + t.NamePart AS varchar(500)),
        Level = p.Level - 1
        FROM
        dbo.NameParts AS t
        INNER JOIN permutations AS p ON t.ID = p.ID
        WHERE 1=1
        AND p.Level > 1
        AND ' ' + p.FullNameVariation + ' ' NOT LIKE '% ' + t.NamePart + ' %'
        )
        SELECT
        ID,
        FullNameVariation
        FROM
        permutations
        WHERE
        Level = 1
        ORDER BY
        ID,
        FullNameVariation
        ;


        Applying the query to this data sample:



        INSERT INTO dbo.NameParts
        VALUES
        (1, 'Sam'), (1, 'Mak'), (1, 'John'),
        (2, 'Donatella'), (2, 'Nobatti'),
        (3, 'Sam'), (3, 'Buca'),
        (4, 'Juan'), (4, 'Soponatime'),
        (5, 'Aaron'), (5, 'Spacemuseum')
        ;


        produces the following output:



        ID FullNameVariation
        -- -----------------
        1 John Mak Sam
        1 John Sam Mak
        1 Mak John Sam
        1 Mak Sam John
        1 Sam John Mak
        1 Sam Mak John
        2 Donatella Nobatti
        2 Nobatti Donatella
        3 Buca Sam
        3 Sam Buca
        4 Juan Soponatime
        4 Soponatime Juan
        5 Aaron Spacemuseum
        5 Spacemuseum Aaron


        You can play with this solution using a live demo at dbfiddle logodb<>fiddle.uk.






        share|improve this answer















        If you split each name into a separate table of the following structure,



        CREATE TABLE dbo.NameParts
        (
        ID int NOT NULL,
        NamePart varchar(30) NOT NULL
        );


        (where ID marks name parts that belong to the same name, to avoid permutation of parts of different names) – then you can use a recursive CTE to produce the permutations:



        WITH
        permutations AS
        (
        SELECT
        ID = t.ID,
        FullNameVariation = CAST(t.NamePart AS varchar(500)),
        Level = COUNT(*) OVER (PARTITION BY t.ID)
        FROM
        dbo.NameParts AS t
        UNION ALL
        SELECT
        ID = t.ID,
        FullNameVariation = CAST(p.FullNameVariation + ' ' + t.NamePart AS varchar(500)),
        Level = p.Level - 1
        FROM
        dbo.NameParts AS t
        INNER JOIN permutations AS p ON t.ID = p.ID
        WHERE 1=1
        AND p.Level > 1
        AND ' ' + p.FullNameVariation + ' ' NOT LIKE '% ' + t.NamePart + ' %'
        )
        SELECT
        ID,
        FullNameVariation
        FROM
        permutations
        WHERE
        Level = 1
        ORDER BY
        ID,
        FullNameVariation
        ;


        Applying the query to this data sample:



        INSERT INTO dbo.NameParts
        VALUES
        (1, 'Sam'), (1, 'Mak'), (1, 'John'),
        (2, 'Donatella'), (2, 'Nobatti'),
        (3, 'Sam'), (3, 'Buca'),
        (4, 'Juan'), (4, 'Soponatime'),
        (5, 'Aaron'), (5, 'Spacemuseum')
        ;


        produces the following output:



        ID FullNameVariation
        -- -----------------
        1 John Mak Sam
        1 John Sam Mak
        1 Mak John Sam
        1 Mak Sam John
        1 Sam John Mak
        1 Sam Mak John
        2 Donatella Nobatti
        2 Nobatti Donatella
        3 Buca Sam
        3 Sam Buca
        4 Juan Soponatime
        4 Soponatime Juan
        5 Aaron Spacemuseum
        5 Spacemuseum Aaron


        You can play with this solution using a live demo at dbfiddle logodb<>fiddle.uk.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 2 days ago

























        answered May 8 at 10:02









        Andriy MAndriy M

        16.5k63776




        16.5k63776



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Database Administrators Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237619%2fgenerate-permutations-and-combination-for-name-column%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

            Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?