我的数据库表字符串列为nvarchar
。
但是当我使用应用程序插入数据时,我忘了添加N'
前缀。因此,网络上的显示不是UTF-8。这会导致很多问题。
如何使用某些T-SQL命令将所有现有表格和所有字符串列类型和数据替换为UTF-8?
答案 0 :(得分:2)
首先,请注意SQL Server不支持UTF-8,it supports UTF-16。因此,您的应用程序代码中可能仍然存在编码问题(您没有显示任何示例数据或代码,因此很难准确说明发生了什么)。
话虽如此,您不能简单地UPDATE
数据将其更改为Unicode:
declare @t table (c nchar(1))
insert into @t select '말'
insert into @t select N'말'
select c, ascii(c), unicode(c) from @t
update @t set c = cast(c as nchar(1))
select c, ascii(c), unicode(c) from @t
正如您所看到的,如果您不使用N
前缀,则字符말将存储为ASCII 63,即使您明确地将其转换为Unicode,SQL Server也无法神奇地知道您这真的意味着它是Unicode代码点47568.所以你唯一能做的就是返回并正确地重新INSERT
所有数据。
答案 1 :(得分:1)
试试这个 -
<强>查询:强>
SELECT
o.table_name
, column_name = c.name
, transform_to = UPPER(t.name) + ' -> ' + CASE WHEN t.name = 'char' THEN 'NCHAR' ELSE 'NVARCHAR' END
, 'ALTER TABLE ' + o.table_name +
' ALTER COLUMN [' + c.name + '] ' +
CASE WHEN t.name = 'char'
THEN 'NCHAR('
ELSE 'NVARCHAR('
END + CASE WHEN c.max_length != -1 THEN CAST(c.max_length * 2 AS NVARCHAR(10)) ELSE 'MAX' END + ')'
FROM sys.columns c WITH (NOWAIT)
JOIN (
SELECT
table_name = '[' + s.name + '].[' + o.name + ']'
, o.[object_id]
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE o.[type] = 'U'
) o ON c.[object_id] = o.[object_id]
JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE t.name IN ('char', 'varchar', 'text')
ORDER BY
o.table_name
, c.column_id
<强>结果:强>
table_name column_name transform_to
------------------------------- ---------------- --------------------- ---------------------------------------------------------------------------------------
[dbo].[Employee] TabelNumber VARCHAR -> NVARCHAR ALTER TABLE [dbo].[Employee] ALTER COLUMN [TabelNumber] NVARCHAR(12)
[dbo].[EmployeeAssigned] EmployeeTypeCD VARCHAR -> NVARCHAR ALTER TABLE [dbo].[EmployeeAssigned] ALTER COLUMN [EmployeeTypeCD] NVARCHAR(30)
[dbo].[EmployeeType] EmployeeTypeCD VARCHAR -> NVARCHAR ALTER TABLE [dbo].[EmployeeType] ALTER COLUMN [EmployeeTypeCD] NVARCHAR(30)
[dbo].[PaymentType] PaymentCode CHAR -> NCHAR ALTER TABLE [dbo].[PaymentType] ALTER COLUMN [PaymentCode] NCHAR(4)
[dbo].[ScheduleDetail] AbsenceCode VARCHAR -> NVARCHAR ALTER TABLE [dbo].[ScheduleDetail] ALTER COLUMN [AbsenceCode] NVARCHAR(50)
[dbo].[ScheduleTemplateDetail] AbsenceCode VARCHAR -> NVARCHAR ALTER TABLE [dbo].[ScheduleTemplateDetail] ALTER COLUMN [AbsenceCode] NVARCHAR(50)
[dbo].[Supplement] WorkFactorCD VARCHAR -> NVARCHAR ALTER TABLE [dbo].[Supplement] ALTER COLUMN [WorkFactorCD] NVARCHAR(50)