为什么这种情况不按预期进行?
此查询无法按预期进行。这是我的示例代码:
create table #test (last_name varchar(20), plan_name varchar(60))
insert #test values ('Alanis', 'Alanis UT Standard Bulk Cut (DRP)')
select last_name
, plan_name
, case when plan_name like '''' + last_name + '%''' then SUBSTRING(plan_name, len(ltrim(rtrim(last_name)))+1, len(ltrim(rtrim(last_name)))+25) else isnull(plan_name, 'NA') end
from #test
现在我期望这要做的是plan_name
以last_name
开始,请掉下前部,因此我留下了文本plan_name
减去前缀last_name
。但这是由于某种原因无法使用的。它只是吐出plan_name
根本没有任何更改。
如果我更明确地进行编码,则可以正常工作:
select last_name
, plan_name
, case when plan_name like 'alanis%' then SUBSTRING(plan_name, len(ltrim(rtrim(last_name)))+1, len(ltrim(rtrim(last_name)))+25) else isnull(plan_name, 'NA') end
from #test
我什至尝试使用cotegname()
函数而不是我的手动串联,并且得到了相同的结果。我验证了我的源表的列实际上是varchar
数据类型(对于last_name
和price_plan
)。我假设我缺少一些细节,但我不知道这是什么。
This query fails to do as intended. Here's my example code:
create table #test (last_name varchar(20), plan_name varchar(60))
insert #test values ('Alanis', 'Alanis UT Standard Bulk Cut (DRP)')
select last_name
, plan_name
, case when plan_name like '''' + last_name + '%''' then SUBSTRING(plan_name, len(ltrim(rtrim(last_name)))+1, len(ltrim(rtrim(last_name)))+25) else isnull(plan_name, 'NA') end
from #test
Now what I'm expecting this to do is if the plan_name
starts with the last_name
, lop off the front part so I'm left with the text of the plan_name
minus that prefixed last_name
. But this doesn't work for some reason. It just spits out the plan_name
without any change at all.
If I code more explicitly, it works just fine:
select last_name
, plan_name
, case when plan_name like 'alanis%' then SUBSTRING(plan_name, len(ltrim(rtrim(last_name)))+1, len(ltrim(rtrim(last_name)))+25) else isnull(plan_name, 'NA') end
from #test
I've even attempted using a QUOTENAME()
function instead of my manual concatenation and I get the same result. I verified that my source table's column is in fact a varchar
data type (for both the last_name
and price_plan
). I'm assuming I'm missing some detail, but I don't know what it is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
last_name
在单个引号中,删除这些额外的引号,这将有效。另一个建议是使用SQL
替换
函数而不是substring
The
last_name
is within the single quotes, remove those extra quotes and this will work.Another suggestion is to use sql
replace
function instead ofsubstring