Tags
Complex SQL Challenges, Complex TSQL Challenge, Interview Qs.SQL SERVER Questions, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Learn complex SQL, Learn SQL, Learn T-SQL, PL/SQL Challenges, Puzzles, Queries for SQL Interview, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL pl/sql puzzles, SQL Puzzles, SQL SERVER Interview questions, SQL SERVER2005/2008, SQL Sudoku, SQLSERVER, T SQL Puzzles, T-SQL Challenge, Tough SQL Challenges, Tough SQL Puzzles, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries
T-SQL Query | [Covert Comma Separated Values to a Table using Cross Apply & XML Puzzle ] – In this puzzle we have to get comma separated values into a table format using XML and Cross Apply operators. Please check out the sample input and expected output for details.
Sample Input
ID | VALUE |
1 | a,b,c |
2 | s,t,u,v,w,x |
Expected Output
Id | SplitedValue |
1 | a |
1 | b |
1 | c |
2 | s |
2 | t |
2 | u |
2 | v |
2 | w |
2 | x |
Rules/Restrictions
- The solution should be should use “SELECT” statement or “CTE”.
- Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com
Script
Use the below script to generate the source table and fill them up with the sample data.
--Create table CREATE TABLE TestCommaUsingCrossApply ( ID INT ,VALUE VARCHAR(100) ) GO --Insert Data INSERT INTO TestCommaUsingCrossApply(ID,VALUE) VALUES (1,'a,b,c'), (2,'s,t,u,v,w,x') --Verify Data select ID,VALUE from TestCommaUsingCrossApply |
Update May 14 | Solutions
-- --------------------------------------- --Sol 1 | Pawan Kumar Khowal --------------------------------------- SELECT Id,SplitedValue FROM ( SELECT ID,cast(('<X>'+replace(e.VALUE,',' ,'</X><X>')+'</X>') as xml) as xmlcol FROM TestCommaUsingCrossApply e ) s OUTER APPLY ( SELECT ProjectData.D.value('.', 'varchar(100)') as SplitedValue FROM s.xmlcol.nodes('X') as ProjectData(D) ) a -- |
Add a comment if you have any other solution in mind. We all need to learn.
Keep Learning
— Using REcursive CTE
;WITH CTERes AS (
SELECT Id, 2 as st, 4 as En ,CAST(SUBSTRING(Value,0,2 )AS varchar(1)) As Value1
from TestCommaUsingCrossApply
UNION ALL
SELECT A.id, B.st+1 as st,B.en+1 as en, CAST(SUBSTRING(A.Value, B.st,B.en) AS varchar(1))As Value1
FROM TestCommaUsingCrossApply A INNER JOIN CTERes B On A.id=B.id
AND B.En-2 <= len(A.VALUE)
)
SELECT Id,Value1 FROM CTERes WHERE Len(Value1)=1 AND Value1′,’ order by id ;
LikeLiked by 1 person