As I intimated in my comment - do not convert numbers to varchars!
There are several different ways of calculating a median in SQL - the one to choose will depend on which version of SQL you are using but you have not shared that information with us.
This article -
What is the fastest way to calculate the median? - SQLPerformance.com[
^] covers most.
Your first problem is going to be to get the data into a usable, sorted, form... putting all the numbers into one long string is also not going to help that process.
Use something like this
select xx, ROW_NUMBER() OVER (ORDER BY xx) AS rnk
FROM (SELECT 1 as ID, a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u FROM #temptable) t
UNPIVOT
(xx for zz in (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u)) as pvt ORDER BY rnk
[EDIT] I have subsequently found this solution
Function to Calculate Median in SQL Server - Stack Overflow[
^] which equates to
SELECT AVG(xx)
FROM
(
select xx, zz, ROW_NUMBER() OVER (ORDER BY xx ASC,zz ASC) AS rnkA, ROW_NUMBER() OVER (ORDER BY xx DESC, zz DESC) AS rnkD
FROM (SELECT 1 as ID, a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u FROM #temptable) t
UNPIVOT
(xx for zz in (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u)) as pvt
) q
WHERE RnkA IN (RnkD, RnkD - 1, RnkD + 1)
I've used the column name (
zz
) as the "disambiguator" mentioned.