This will produce a 5x5 square of 5, 5-letter words that read the same across as down.
WITH UNIQUEnTuples (n, Tuples) AS
(
SELECT 1, CAST(strcol AS VARCHAR(max))
FROM @t
UNION ALL
SELECT 1 + n.n, t.strcol + ',' + n.Tuples
FROM @t t JOIN UNIQUEnTuples n ON t.strcol < n.Tuples
WHERE CHARINDEX(t.strcol, n.Tuples) = 0 AND n < 2
),
MatrixOfLetters AS
(
SELECT rn, cn, RandomLetter=MAX(rl)
FROM UNIQUEnTuples a
CROSS APPLY
(
SELECT Tuples=CASE n WHEN 1 THEN Tuples + ',' + Tuples ELSE Tuples END
,RandomLetter=CHAR(65+ABS(CHECKSUM(NEWID()))%26)
) b
CROSS APPLY
(
-- VALUES (CAST(LEFT(b.Tuples, 1) AS INT), CAST(RIGHT(b.Tuples, 1) AS INT), RandomLetter)
-- ,(CAST(RIGHT(b.Tuples, 1) AS INT), CAST(LEFT(b.Tuples, 1) AS INT), RandomLetter)
SELECT CAST(LEFT(b.Tuples, 1) AS INT), CAST(RIGHT(b.Tuples, 1) AS INT), RandomLetter
UNION ALL SELECT CAST(RIGHT(b.Tuples, 1) AS INT), CAST(LEFT(b.Tuples, 1) AS INT), RandomLetter
) c (rn, cn, rl)
GROUP BY rn, cn
)
SELECT rn, cn, RandomLetter
INTO #Temp
FROM MatrixOfLetters;
SELECT word=
(
SELECT RandomLetter + ''
FROM #Temp b
WHERE a.rn = b.rn
ORDER BY cn
FOR XML PATH('')
)
FROM #Temp a
GROUP BY rn
ORDER BY rn;
GO
DROP TABLE #Temp;
It is not guaranteed to produce words but you could run the result against a dictionary of 5 letter words and keep any that match 5x5.
Explanation? What you want an explanation too? Jeez. OK.
Start here: Generating n-Tuples with SQL[/url]
The CROSS APPLY VALUES thing is here: An Alternative (Better?) Method to UNPIVOT (SQL Spackle) [/url]
Then for the concatenation, read this: Creating a comma-separated list (SQL Spackle) [/url]
If you still have questions let me know.
That was fun! 😛 Now on to serious business.
Edit: Ooops! Forgot CROSS APPLY VALUES is not available in SQL 2005, so I modified it to use SELECT/UNION ALL/SELECT but the concept is the same.
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St