简体   繁体   English

在SQL Server中将varchar转换为nvarchar失败

[英]Converting varchar to nvarchar in SQL Server failed

I have SQL Server table that contains columns of type varchar(50) as a result of a CSV import using the SQL Server Import wizard. 我有SQL Server表,其中包含使用SQL Server导入向导进行CSV导入的varchar(50)类型的列。

I was wanting to know how I can change this data type to nvarchar(9) without getting a SQL Server truncation error. 我想知道如何在不收到SQL Server截断错误的情况下将此数据类型更改为nvarchar(9)

I tried doing a bulk update to set the data types and column sizes that I need but still had the truncation error message when I tried to load the csv into the empty database table I created (with my required data types that I need). 我尝试进行批量更新以设置我需要的数据类型和列大小但当我尝试将csv加载到我创建的空数据库表(我需要的所需数据类型)时仍然有截断错误消息。

Grateful for any help. 感谢任何帮助。

Since you are willing to lose data and nvarchar will only be able to store 9 non-unicode charaters, then select only 9 characters from your source table, You do the truncation rather than Sql server doing it for you. 由于您愿意丢失数据并且nvarchar只能存储9个非unicode字符,然后从源表中只选择9个字符,您执行截断而不是Sql server为您执行此操作。

The Following Query will trim any White spaces from the strings, Then take only 9 characters from the string and convert them to NVARCHAR(9) for you..... 以下查询将修剪字符串中的任何空格,然后从字符串中只取9个字符并将它们转换为NVARCHAR(9)...

CREATE TABLE New_TABLE (Col1 NVARCHAR(9), Col2 NVARCHAR(9))
GO

INSERT INTO New_TABLE (Col1, Col2)
SELECT CONVERT(NVARCHAR(9),LEFT(LTRIM(Col1), 9))  
      ,CONVERT(NVARCHAR(9),LEFT(LTRIM(Col2), 9))
FROM Existing_Table
GO

Bulk insert into temp table with varchar(50) and insert to actual table 使用varchar(50)批量插入临时表并插入到实际表中

insert into tableName 
select cast(tempcolumn as nvarchar(9)) from temptable

And it is also important to check field types of destination table. 检查目标表的字段类型也很重要。 Just spent 3 hours because of same error with random casting, trimming, substring and at the end noticed, that colleague created table with too short field lengths. 由于同样的错误,随机播放,修剪,子字符串花了3个小时,最后注意到,该同事创建的字段长度太短。 I hope it helps somebody... 我希望它有助于某人......

如果在导入/导出任务期间遇到此错误,则可以在“编写查询以指定要传输的数据”选项中将select cast(xxx as nvarchar(yyy)) as someName

varchar and nvarchar only use the length needed for the data stored. varchar和nvarchar仅使用存储数据所需的长度。 If you need unicode support certainly convert to nvarchar, but modifying it from 50 to 9 - what is the point? 如果你需要unicode支持肯定会转换为nvarchar,但是将它从50修改为9 - 这有什么意义呢?

If your data is ALWAYS exactly 9, consider using char(9), and following one of the transformation suggestions above... 如果您的数据总是完全为9,请考虑使用char(9),并遵循以上转换建议之一...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM