Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用子字符串或charindex匹配破折号后的数据_Sql_Sql Server - Fatal编程技术网

Sql 使用子字符串或charindex匹配破折号后的数据

Sql 使用子字符串或charindex匹配破折号后的数据,sql,sql-server,Sql,Sql Server,在这种情况下,我必须将用户输入数据与msql数据表中的数据相匹配 假设用户输入为123,数据库值为1111-123或15454454aa-4545。所以我必须在左侧破折号后匹配数据 这是我的问题,但我无法得到它 select left(column1,LEN(column1)-CHARINDEX('-',column1)) from table where column1='123' 这应该做到: select left(column1,LEN(column1)-CHARINDEX('

在这种情况下,我必须将用户输入数据与msql数据表中的数据相匹配

假设用户输入为
123
,数据库值为
1111-123
15454454aa-4545
。所以我必须在左侧破折号后匹配数据

这是我的问题,但我无法得到它

select left(column1,LEN(column1)-CHARINDEX('-',column1)) 
from table where column1='123'
这应该做到:

select 
  left(column1,LEN(column1)-CHARINDEX('-',column1))
  --the items in the select portion aren't important for 
  --finding a match, this part can be anything, column name, * etc.      
  from table where column1 LIKE '%-' + '123'

如果搜索字符串可以位于破折号之后的任何位置

Declare @YourTable table (column1 varchar(150))
Insert into @YourTable values
('1111-123'),
('1111-###123###'),
('15454454aa-4545')

Declare @Search varchar(50) = '123'

Select * from @YourTable 
 Where column1 like '%-%'+@Search+'%'
返回

column1
1111-123
1111-###123###
您可以使用从
列1
中剪切所需内容:

select * 
from YourTable 
where SUBSTRING(column1,CHARINDEX('-',column1)+1,LEN(column1)) ='123'
或:

或:

或:

或:


假设用户输入为123,数据库值为1111-123或15454454aa-4545,指定输出简化了问题。您可以在where子句中使用select语句,因为它是
where left(column1,LEN(column1)-CHARINDEX('-',column1))=“123”如果DASH的左右两边有特殊的含义,考虑将它们存储在单独的列中。您还可以添加一个将它们重新连接在一起的。您的方法使所有值立即可用。Hi Jan-添加一些上下文后,您的纯代码答案会更好。例如,您可以解释此代码如何以及为什么用于解决提问者的特定问题;这样,它对其他寻求类似问题帮助的读者也会更有用。
select * 
from YourTable 
where SUBSTRING(column1,CHARINDEX('-',column1)+1,LEN(column1)) ='123'
select *
from YourTable 
where PARSENAME(REPLACE(column1,'-','.'),1) ='123'
select *
from YourTable 
where RIGHT(column1,LEN(column1)-CHARINDEX('-',column1)) ='123'
select *
from YourTable 
where STUFF(column1,1,CHARINDEX('-',column1),'')='123'
select *
from YourTable 
where column1 LIKE '%-'+'123'