我正在编写存储过程,我需要将SQL Server变量与列进行比较。问题是,如果我的SQL变量是一个与列类型长度不同的VARCHAR,它就不会匹配。
例:
我们说,我有一个表types
,其列name
的类型为VARCHAR(100)
。运行下面的代码不会给我任何结果:
DECLARE @type VARCHAR(20);
SET @type = 'My Type Name';
select * from types where name = @type
但是,运行此查询会找到我的列:
DECLARE @type VARCHAR(100);
SET @type = 'My Type Name';
select * from types where name = @type
现在,我希望能够以第一种方式执行此操作,尤其是因为如果我修改了列,我不希望此查询开始失败。谁能告诉我我做错了什么?
编辑:
这是我的列架构:
查询:
DECLARE @event_type VARCHAR(20);
SET @event_type = 'Price Increase Notification';
select * from events.types where name = @event_type
输出:
查询:
DECLARE @event_type VARCHAR(100);
SET @event_type = 'Price Increase Notification';
select * from events.types where name = @event_type
输出:
答案 0 :(得分:1)
以下内容将如您所述:
CREATE TABLE #types
(
type VARCHAR(100)
)
INSERT INTO #types (type) VALUES ('My Type Name')
-- returns 1 row
select * from #types
-- returns 0 rows
DECLARE @type VARCHAR(10);
SET @type = 'My Type Name';
select * from #types where type = @type
-- returns 1 row
DECLARE @long_type VARCHAR(100);
SET @long_type= 'My Type Name';
select * from #types where type = @long_type
drop table #types
重点是DECLARE @type VARCHAR(10); SET @type = 'My Type Name';
实际上会将您的变量设置为'My Type Na'
(长度= 10)。
因此,如果您的值比您的变量长,则该变量将设置为截断值。没有警告,没有错误。如果您尝试将其等同于原始(更长)值,您会发现它们不相等。
答案 1 :(得分:1)
您编辑过的示例:
DECLARE @event_type VARCHAR(20);
SET @event_type = 'Price Increase Notification';
select * from events.types where name = @event_type
您将@event_type设置为的字符串是27个字符,因此它被截断为20个字符,因此没有匹配。
如果列长度发生变化,我可能会做的是将@event_type声明为varchar(max)
答案 2 :(得分:0)
这是我要做的 select * from events.types其中ltrim(rtrim(name))= @event_type