简体   繁体   中英

Sort by column that contains null values?

I'd figure this would be an easy problem to solve, but I've been googling like crazy trying to find an answer and I'm just not getting one.

I want to sort the results based on a column that contains null values. SQL Server seems to thinks that's a bad idea. I've tried limiting them using ISNULL , LIKE , as well as a few other various methods to try to get this to work and it's just not happening.

SELECT c1
FROM t1
WHERE c1 IS NOT NULL
ORDER BY c1 DESC

SQL Server gives me this error: The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.

Like I said, I've been googling like crazy trying to find an answer to this simple problem and it's just not happening.

c1 is text, ntext, or image

so as the error says you can't order by them

try casting the text/ntext to varchar(max) that should do it.

SELECT c1
FROM t1
WHERE c1 IS NOT NULL
ORDER BY convert(varchar(max),c1) DESC
ORDER BY cast(c1 as varchar(max)) DESC

and consider switching the column c1 's type to varchar(max) . text is an obsolete data type .

I found something that says you can only sort varchar. Try this bit of code.

SELECT c1 FROM t1 WHERE c1 IS NOT NULL ORDER BY cast(c1 as varchar(MAX))

src:http://twogeeks.mindchronicles.com/?p=7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM