My database is hosted on Microsoft SQL Server 2012 and I need to write a T-SQL query to pull the length of each column of a specific table.
Assuming my database is called mydatabase
and the table is called table1
with 3 columns (namely col1
, col2
and col3
), how do I write my sql query to get that information?
Ideally, I want the output to be something like this:
ColumnName Length
col1 50
col2 30
col3 25
Additional info: I will need to run this query on several other tables where I don't know the number or names of the columns therein. So the query should output the names of the columns with their respective column length.
3条答案
按热度按时间k4ymrczo1#
I assume by length you mean, for example, that if it is a
varchar(50)
it has a length of 50. If it's adecimal(18,2)
then you want to know Scale18
, Precision2
. This should help:hmmo2u0o2#
If you are looking for a Query that will return the Maximum permitted length of a column, Then you can View it from the
INFORMATION_SCHEMA.COLUMN
viewOr if you are looking for the Maximum Lenght of the Data Stored is Each Column Use MAX() and LEN() function
klr1opcd3#
You can use
COL_LENGTH
to get this (more information can be found here )You could write something like the following:
EDIT:
With the extra information provided I think the below is what you are looking for:
You will probably have to add a where clause in as this is currently looking for everything on a database.
By joining the
sys.columns
andsys.tables
withinformation_schema.columns
You can find the length of columns/tables with out needing to know the name.