Due to storing values from language specific diacritics (Spanish, French, German) I am trying to change the datatype of a column to Unicode datatype.
So all column datatype to its respective Unicode datatype.
For all tables in a specific database.
Can it be possible to do in a single statement? Because doing with alter
statement is time consuming.
ALTER TABLE dbo.Employee
ALTER COLUMN FirstName NVARCHAR(255) NOT NULL
Many thanks.
First we create a temporary table and define the variables we need for the changes.
Then we fill the table by fetching the columns that need to change. I entered the fetch command below and everything is clear.
Then, for each row in the table, we make the desired changes in the database.
Also, a column in a table may have a value of NULL
, so you must replace the NULL
values with a value before changing the column. I replaced the NULL
values with a value of 0
.
The code below works perfectly and correctly.
Only I entered dbo
for schema name
in search of columns. See what your database schema name is
--Container to Insert Id which are to be iterated
Declare @temp1 Table
(
tablename varchar(100),
columnname varchar(100),
columnlength varchar(100),
columntype varchar(100)
)
--Container to Insert records in the inner select for final output
Insert into @temp1
SELECT t.TABLE_NAME,c.COLUMN_NAME,c.CHARACTER_MAXIMUM_LENGTH,c.DATA_TYPE FROM information_schema.tables t
join INFORMATION_SCHEMA.COLUMNS c on t.TABLE_NAME = c.TABLE_NAME
WHERE t.table_schema='dbo'
and (DATA_TYPE = 'varchar' OR DATA_TYPE = 'char')
-- Keep track of @temp1 record processing
Declare @tablename varchar(100)
Declare @columnname varchar(100)
Declare @columnlength varchar(100)
Declare @columntype varchar(100)
Declare @SQL VarChar(1000)
Declare @vary varchar(100)
Declare @final varchar(1000)
While((Select Count(*) From @temp1)>0)
Begin
Set @tablename=(Select Top 1 tablename From @temp1)
Set @columnname=(Select Top 1 columnname From @temp1)
Set @columnlength=(Select Top 1 columnlength From @temp1)
Set @columntype=(Select Top 1 columntype From @temp1)
if(@columntype = 'varchar')
Set @columntype='nvarchar'
else
Set @columntype='nchar'
--set null value with 0 value
SELECT @SQL = 'UPDATE ' + @tablename + ' SET ' + @columnname + ' = 0 WHERE ' + @columnname + ' IS NULL'
Exec ( @SQL)
SELECT @SQL = 'ALTER TABLE '
SELECT @SQL = @SQL + @tablename
select @vary = ' ALTER COLUMN ' + @columnname + ' ' + @columntype + '(' + @columnlength + ') NOT NULL'
select @final = @sql + @vary
--select @final
Exec ( @final)
Delete @temp1 Where tablename=@tablename and columnname = @columnname
End
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.