SUBSTRING
返回字符、binary、text 或 image 表达式的一部分。语法
SUBSTRING ( e­xpression , start , length ) 参数
e­xpression
是字符串、二进制字符串、text、image、列或包含列的表达式。不要使用包含聚合函数的表达式。
start
是一个整数,指定子串的开始位置。
length
是一个整数,指定子串的长度(要返回的字符数或字节数)。oracleIn oracle/PLSQL, the substr functions allows you to extract a substring from a string.The syntax for the substr function is:substr( string, start_position, [ length ] )
说明:
string is the source string.
start_position is the position for extraction. The first position in the string is always 1.
length is optional. It is the number of characters to extract. If this parameter is omitted, substr will return the entire string.For example:
     substr('This is a test', 6, 2)          would return 'is'
     substr('This is a test', 6)              would return 'is a test'
     substr('TechOnTheNet', 1, 4)     would return 'Tech'
     substr('TechOnTheNet', -3, 3)    would return 'Net'
     substr('TechOnTheNet', -6, 3)     would return 'The'
     substr('TechOnTheNet', -8, 2)     would return 'On'

解决方案 »

  1.   

    CHARINDEX函数返回字符或者字符串在另一个字符串中的起始位置。CHARINDEX函数调用方法如下: 
           CHARINDEX ( expression1 , expression2 [ , start_location ] )       Expression1是要到expression2中寻找的字符中,start_location是CHARINDEX函数开始在expression2中找expression1的位置。       CHARINDEX函数返回一个整数,返回的整数是要找的字符串在被找的字符串中的位置。假如CHARINDEX没有找到要找的字符串,那么函数整数“0”。让我们看看下面的函数命令执行的结果:      CHARINDEX('SQL', 'Microsoft SQL Server')      这个函数命令将返回在“Microsoft SQL Server”中“SQL”的起始位置,在这个例子中,CHARINDEX函数将返回“S”在“Microsoft SQL Server”中的位置11。
    接下来,我们看这个CHARINDEX命令:      CHARINDEX('7.0', 'Microsoft SQL Server 2000')      在这个例子中,CHARINDEX返回零,因为字符串“7.0” 不能在“Microsoft SQL Server”中被找到。接下来通过两个例子来看看如何使用CHARINDEX函数来解决实际的T-SQL问题。
      

  2.   

    @cwhere varchar(400) 
    @invcode varchar(300) 
    declare @ind1 int,@ind2 int
    select @ind1=charindex('zinvcode =',@cwhere) + 11 --@cwhere 中'zinvcode ='的起始位置
    , @ind2=charindex('''', @cwhere, @ind1) --@cwhere 中在'zinvcode ='后单引号第一次出现的位置
    , @invcode=substring(@cwhere, @ind1, @ind2-@ind1) --从@cwhere中截取子串:起始位置为@ind1,长度为@ind2-@ind1
    , @invcode=ltrim(rtrim(@invcode)) --去掉@invcode前后的空格 print @invcode 
      

  3.   

    其实这只是用到了2个SQL的函数而已
    charindex和substring
    charindex是字符定位
    ltrim和rtrim和清空左右的空格。
    比如说你这个@cwhere='aaaaazinvcodebbbbb'cccc'dddd'substring(@cwhere,charindex('zinvcode =',@cwhere)+11,
    --charindex('zinvcode =',@cwhere)+11=17
    --zinvcode =该字符串时11位的。charindex('''',@cwhere,charindex('zinvcode =',@cwhere)+11)-
    --该处取得@cwhere中'zinvcode ='字符串中的''的位置(charindex('zinvcode =',@cwhere)+11))
      
    )
    其实整段的意思就是截取@cwhere中'zinvcode ='之后到''之间的数据
    如上例子的字符串中的5个b
      

  4.   

    另外还有一个问题,在这个语句中charindex('''',@cwhere,charindex('zinvcode =',@cwhere)+11)
    为什么会有四('''')个引号, 在这里起什么作用
      

  5.   

    4是就是2个嘛,sql里字符使用' '包括在里面的
      

  6.   

    因为'需要转义,你执行下print('''')就知道了