我有两列:
简单的事情无法弄清楚如何。
select *
from plant.carrier
where carrier_id like 'NT'
这会产生表达式错误
SELECT *
FROM plant.carrier
WHERE RTrim(CAST([carrier_id] As VarChar) = 'NT'
id列
CREATE TABLE [plant].[carrier](
[carrier_id] [nchar](4) NOT NULL,
[name] [nvarchar](30) NOT NULL,
CONSTRAINT [PK_carrier] PRIMARY KEY CLUSTERED
(
[carrier_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS =enter code here ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
答案 0 :(得分:2)
要比较nchar和varchar,您需要将char转换为varchar并比较两个varchars:
RTrim(CAST([nCharColumn] As VarChar)
<强>更新强>
以下是完整示例:
create table test (
f nchar(20))
insert into test values('nt')
insert into test values('st')
declare @s varchar(20) = 'nt'
select * from test where rtrim(cast(f as varchar)) = @s
更新2
CREATE TABLE [carrier](
[carrier_id] [nchar](4) NOT NULL,
[name] [nvarchar](30) NOT NULL,
CONSTRAINT [PK_carrier] PRIMARY KEY CLUSTERED
(
[carrier_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
insert into carrier values('nt', 'nt')
insert into carrier values('st', 'st')
declare @s varchar(20) = 'nt'
select * from carrier where rtrim(cast([carrier_id] as varchar)) = @s
这也适合我。它返回一条记录。
答案 1 :(得分:2)
如果您Read The Documentation,您会发现[var]char
和n[var]char
之间的转换是隐含的,所以请说
where x.some_char_column = y.some_nchar_column
应该工作得很好......除非列定义的排序规则不同。那你可能有问题。
答案 2 :(得分:1)
在比较字符串值时不要使用rtrim。无论数据类型是(n)char还是(n)varchar,sql server都会忽略任何字符串右侧的空格以进行相等性检查。
对原件的这些轻微修改都应该可以正常工作。它们都与您发布的表格一起使用。
select *
from carrier
where carrier_id like 'NT%'
SELECT *
FROM carrier
WHERE [carrier_id] = 'NT'