问题
I want to find the longest VARCHAR
in a specific column of a SQL Server table.
Here's an example:
ID = INT IDENTITY
DESC = VARCHAR(5000)
ID | Desc
---|-----
1 | a
2 | aaa
3 | aa
What's the SQL to return 3? Since the longest value is 3 characters?
回答1:
Use the built-in functions for length and max on the description column:
SELECT MAX(LEN(DESC)) FROM table_name;
Note that if your table is very large, there can be performance issues.
回答2:
for mysql its length not len
SELECT MAX(LENGTH(Desc)) FROM table_name
回答3:
Watch out!! If there's spaces they will not be considered by the LEN method in T-SQL. Don't let this trick you and use
select max(datalength(Desc)) from table_name
回答4:
For Oracle, it is also LENGTH instead of LEN
SELECT MAX(LENGTH(Desc)) FROM table_name
Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.
If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.
回答5:
Gives the Max Count of record in table
select max(len(Description))from Table_Name
Gives Record Having Greater Count
select Description from Table_Name group by Description having max(len(Description)) >27
Hope helps someone.
回答6:
SELECT MAX(LEN(Desc)) as MaxLen FROM table
回答7:
For sql server (SSMS)
select MAX(LEN(ColumnName)) from table_name
This will returns number of characters.
select MAX(DATALENGTH(ColumnName)) from table_name
This will returns number of bytes used/required.
IF some one use varchar then use DATALENGTH
.More details
回答8:
SELECT TOP 1 column_name, LEN(column_name) AS Lenght FROM table_name ORDER BY LEN(column_name) DESC
回答9:
Many times you want to identify the row that has that column with the longest length, especially if you are troubleshooting to find out why the length of a column on a row in a table is so much longer than any other row, for instance. This query will give you the option to list an identifier on the row in order to identify which row it is.
select ID, [description], len([description]) as descriptionlength
FROM [database1].[dbo].[table1]
where len([description]) =
(select max(len([description]))
FROM [database1].[dbo].[table1]
来源:https://stackoverflow.com/questions/9592287/retrieve-the-maximum-length-of-a-varchar-column-in-sql-server