【问题标题】:How do I fix the substring to use like in SQL code?如何修复子字符串以在 SQL 代码中使用?
【发布时间】:2015-04-23 16:23:51
【问题描述】:

我的声明:

declare @status varchar(255);
set @status = 'seated'

这就是我的表结构的样子

**description**
Seated, Unpaid
Seated, Paid
Return
Seating Failed
Unseated, Paid
Upgraded
Ticketed, Paid
Unseatable
etc. 

我的通用代码:

select  description
from    tr_status
where   description like Substring(@status,0,LEN(status))

我想做的是说出描述字段“就位”在其中的任何位置(或作为我的参数传递的任何值)。仅返回作为描述的一部分存在的那些行。

所以只有这些:

Seated, Unpaid
Seated, Paid
Unseated, Paid

【问题讨论】:

  • 我之后的所有3个解决方案都是错误的,字符串连接是用||完成的不带 +
  • @MariM 对不起,我错过了 oracle,可能是另一个问题。我应该删除我的评论吗?或者把它留在那里,让人们知道你的回答?

标签: sql sql-server parameters substring sql-like


【解决方案1】:
SELECT  description
FROM    tr_status
WHERE   description LIKE '%' + @status + '%'

% 在 SQL 中是一个通配符,所以会匹配任何一系列的字符。 LIKE 语句允许在此通配符旁边连接变量,从而产生您所要求的搜索。

【讨论】:

  • 我知道它是一个通配符,但我不知道如何将它链接到参数。我没有意识到简单地连接它是有效的。
【解决方案2】:

您不需要为此使用子字符串:

WHERE description LIKE @status 

应该做的伎俩。或者更糟糕的情况:

WHERE description LIKE '%' + @status + '%'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多