Because I want to convert the columns to not be varchar(MAX)
I want to see the maximum datalength for each column to decide what the new size should be.
I have this query for finding all my (n)varchar(MAX)
columns.
SELECT [TABLE_NAME], [COLUMN_NAME]
FROM information_schema.columns
WHERE DATA_TYPE IN ('varchar', 'nvarchar')
AND CHARACTER_MAXIMUM_LENGTH = -1
ORDER BY TABLE_NAME, COLUMN_NAME
For instance I have a customer table and among the results the following is output for my customers table
+------------+--------------+
| TABLE_NAME | COLUMN_NAME |
+------------+--------------+
| customers | name |
| customers | address |
| customers | postal_code |
| customers | city |
| customers | email |
| customers | phone_number |
+------------+--------------+
By running the following queries:
SELECT MAX(DATALENGTH(name)) FROM customers
SELECT MAX(DATALENGTH(address)) FROM customers
SELECT MAX(DATALENGTH(postal_code)) FROM customers
SELECT MAX(DATALENGTH(city)) FROM customers
SELECT MAX(DATALENGTH(email)) FROM customers
SELECT MAX(DATALENGTH(phone_number)) FROM customers
I can get the result I want, but I'd really like for it to be just one query returning something like:
+------------+--------------+------------+
| TABLE_NAME | COLUMN_NAME | Datalength |
+------------+--------------+------------+
| customers | name | 93 |
| customers | address | 122 |
| customers | postal_code | 6 |
| customers | city | 44 |
| customers | email | 75 |
| customers | phone_number | 18 |
+------------+--------------+------------+
I have tried
SELECT
[TABLE_NAME], [COLUMN_NAME],
(SELECT MAX(DATALENGTH(COLUMN_NAME))
FROM TABLE_NAME) AS 'MaxContentLength'
FROM information_schema.columns
WHERE DATA_TYPE IN ('varchar', 'nvarchar')
AND CHARACTER_MAXIMUM_LENGTH = -1
ORDER BY TABLE_NAME, COLUMN_NAME
But I get this error:
Msg 208, Level 16, State 1, line 1
Invalid object name 'TABLE_NAME'
How do I fix this issue (or is there another way to do what I want?)
4条答案
按热度按时间lo8azlld1#
This is my approach to solve your question, maybe not the fastest one.
9w11ddsr2#
Is this correct for you ?
bvjxkvbb3#
Those multiple queries that use DATALENGTH can be combined in one.
untested notepad scribble
llew8vvj4#
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH, DATALENGTH(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE IN ('VARCHAR', 'NVARCHAR', 'CHAR', 'NCHAR') AND CHARACTER_MAXIMUM_LENGTH < DATALENGTH(COLUMN_NAME)