Chinese_PRC_CI_AS and SQL_Latin1_General_CP1_CI_AS类型错误

时间:2023-03-09 17:06:28
Chinese_PRC_CI_AS and SQL_Latin1_General_CP1_CI_AS类型错误

在编写存储过程时,经常会用到临时表,而且往往会使用临时表与正式表相关联。

当临时表与正式表关联的字段是字符类型的时候,因为临时表创建的字符类型会默认数据库的编码,而正式表的字符编码可能不同,那么这个时候,需要对正式表的该字段加上collate database_default 语句来进行关联,例句:

create table Test
(
Name nvarchar(30),
Age int
)
go

create table #temp
(
Name nvarchar(30),
Class nvarchar(30)
)
go

insert into Test select '张三',18
union all select '李四',22
union all select '王五',20

insert into #temp select '张三','大一'
union all select '李四','大四'
union all select '王五','大二'

select t.*,te.Class from Test t inner join #temp te on t.Name collate database_default=te.Name

drop table #temp
drop table Test

通过这种方式就能在不同服务器的sqlserver上查询,再也不用担心突然报一个编码不正确的问题