我如何在SQL中使用子字符串?

时间:2010-09-03 08:55:10

标签: c# sql sql-server-2005

  

可能重复:
  How can I rearrange string with SQL?



Declare @CustTotalCount as int
Declare @CustMatchCount as int 
 select @CustTotalCount = count(*)  from ENG_CUSTOMERTALLY

 select @CustMatchCount = count(*)  from Task  where MPDReference in(
 select ENG_CUSTOMERTALLY_CUSTOMERTASKNUMBER from dbo.ENG_CUSTOMERTALLY)

if(@CustTotalCount>@CustMatchCount)
select distinct
 substring(ENG_CUSTOMERMYCROSS_MYTECHNIC_TASK_NO, charindex('-', ENG_CUSTOMERMYCROSS_MYTECHNIC_TASK_NO)
 + 1, 1000)
  from dbo.ENG_CUSTOMERMYCROSS where
 ENG_CUSTOMERMYCROSS_CUSTOMER_NUMBER in(
select ENG_CUSTOMERTALLY_CUSTOMERTASKNUMBER from ENG_CUSTOMERTALLY1
except
select MPDReference from Task )

我可以转换下面的字符串数据

  • A320-200001-01-1(1)
  • A320-200001-01-1(2)
  • A320-200001-01-1(1)

  • 200001-01-1(1)
  • 200001-01-1(2)
  • 200001-01-1(1)

但我需要

  • 200001-01-1
  • 200001-01-1
  • 200001-01-1

distict ---> 200001-01-1 我该怎么做SQL和C#?

2 个答案:

答案 0 :(得分:0)

你可以

SELECT DISTINCT SUBSTRING(....) FROM ...

答案 1 :(得分:0)

我也在重复的问题中给出了这个答案。

这是一种使用PATINDEX的技术,它可以使用通配符。

SUBSTRING(ENG_CUSTOMERMYCROSS_MYTECHNIC_TASK_NO,
        PATINDEX('%[0-9]%', ENG_CUSTOMERMYCROSS_MYTECHNIC_TASK_NO),
        PATINDEX('%(%', ENG_CUSTOMERMYCROSS_MYTECHNIC_TASK_NO)
                 - PATINDEX('%[0-9]%', ENG_CUSTOMERMYCROSS_MYTECHNIC_TASK_NO)
                )

子字符串的开头是第一个数值(%[0-9]%)的位置。长度值是第一个括号的位置('%(%')减去起始位置。