Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : Nvarchar to Varchar

I have a table with two columns, one is of type Varchar and the other in NVarchar.

I want to update all the rows so VarcharField = NVarcharField.

It won't let me because some of the rows contain chars that are not allowed in varchar column with the current code page.

How can I find these rows?

Is it possible to remove any char that doesn't fit the specific code page I'm using?

SQL Server 2012.

like image 629
Itay.B Avatar asked Apr 12 '26 18:04

Itay.B


2 Answers

You can find the rows by attempting to convert the nvarchar() col to varchar():

select nvarcharcol
from t
where try_convert(varchar(max), nvarcharcol) is null;
like image 153
Gordon Linoff Avatar answered Apr 15 '26 06:04

Gordon Linoff


Try this..

to find the rows with values that are not supported by varchar

declare @strText nvarchar(max)
set @strText = 'Keep calm and say தமிழன்டா'

select  cast(@strText as varchar(max)) col1 , N'Keep calm and say தமிழன்டா' col2

Here @strText has non-english chars, When you try to cast that into varchar the non-english chars turns into ????. So the col1 and col2 are not equal.

select nvar_col
from tabl_name
where nvar_col != cast(nvar_col as varchar(max))

Is it possible to remove any char that doesn't fit the specific code page I'm using?

update tabl_name 
    set nvar_col = replace(cast(nvar_col as varchar(max)),'?','')
where nvar_col != cast(nvar_col as varchar(max))

Replace ? with empty string and update them.

like image 35
Sankar Avatar answered Apr 15 '26 06:04

Sankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!