Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Changing Data Types

Author  Topic 

evanburen
Posting Yak Master

167 Posts

Posted - 2008-11-14 : 09:56:24
Hi

I'm using the below to find all of the fields defined as text or ntext and I want to convert all of these to varchar(max). How would I do this without changing them one at a time? Thanks.

SELECT table_name,column_name, data_type
FROM INFORMATION_SCHEMA.Columns
WHERE data_type='text' or data_type='ntext'

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-14 : 10:11:10
[code]SELECT 'ALTER TABLE ' + TABLE_NAME + ' ALTER COLUMN ' + COLUMN_NAME + ' VARCHAR(MAX);'
FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE = 'TEXT'

UNION ALL

SELECT 'ALTER TABLE ' + TABLE_NAME + ' ALTER COLUMN ' + COLUMN_NAME + ' NVARCHAR(MAX);'
FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE = 'NTEXT'[/code]
Run the query and copy the result to a query window and run the pasted code.


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

evanburen
Posting Yak Master

167 Posts

Posted - 2008-11-14 : 10:33:23
Works great. Thanks.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-11-14 : 11:12:23
You can use QUOTENAME() function for TABLE_NAME and COLUMN_NAME if they contain any special character, such as space, brackets or quotes.

SELECT 'ALTER TABLE ' + QUOTENAME(TABLE_NAME) + ' ALTER COLUMN ' + QUOTENAME(COLUMN_NAME) + ' VARCHAR(MAX);'
FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE = 'TEXT'

UNION ALL

SELECT 'ALTER TABLE ' + QUOTENAME(TABLE_NAME) + ' ALTER COLUMN ' + QUOTENAME(COLUMN_NAME) + ' NVARCHAR(MAX);'
FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE = 'NTEXT'



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page
   

- Advertisement -