使用CHARINDEX作为Length参数的T-SQL SUBSTRING

时间:2018-12-12 14:05:43

标签: sql-server tsql split sql-server-2014

我有以下sql。在where之后的AND语句应确保名称中确实存在第二个空格,例如在中间名称/首字母之后。此列中的名称是相反的顺序,即Last,First,Middle。我正在尝试获取名字,如果有的话,它将是第二个位置的名字。我得到的长度参数无效,并且不确定为什么,我认为我的AND语句会解决这个问题。

样本数据:

Consultant_Contacted
Sample Name Test
Sample Name S
Name S Sample2

预期结果:

Consultant_Last_Name | Consultant_First_Name
Sample               | Name
Name                 | Sample2

我通过查找A.Ordering_pty_name = ''

来处理名字的倒序
WHEN A.Ordering_pty_name = ''
AND (CHARINDEX(' ', A.Consultant_Contacted, CHARINDEX(' ', A.Consultant_Contacted) + 1) + 1) > 0
    THEN UPPER(
        RTRIM(
            LTRIM(
                SUBSTRING(
                    A.Consultant_Contacted
                    , CHARINDEX(' ', A.Consultant_Contacted, 1) 
                    --, 100
                    , (
                        CHARINDEX(
                            ' '
                            , A.CONSULTANT_CONTACTED
                            , CHARINDEX(
                                ' '
                                , A.CONSULTANT_CONTACTED
                                ) + 1
                            ) + 1 
                        ) - 
                        (
                        CHARINDEX(
                            ' '
                            , A.CONSULTANT_CONTACTED
                            , 1
                            )
                        )
                    )
                )
            )
        )

2 个答案:

答案 0 :(得分:1)

解析名称可能是一个滑坡。

您可以使用parsename(),但是XML方法对我来说似乎更直观。

示例

Declare @YourTable table (Consultant_Contacted varchar(100))
Insert Into @YourTable values
('Sample Name Test'),
('Sample Name S'),
('Name S Sample2')

Select Distinct
       Last_Name  = Pos1
      ,First_Name = case when len(Pos2)=1 then Pos3 else Pos2 end
 From  @YourTable A
 Cross Apply (
                 Select Pos1 = n.value('/x[1]','varchar(100)')
                       ,Pos2 = n.value('/x[2]','varchar(100)')
                       ,Pos3 = n.value('/x[3]','varchar(100)')
                  From  (Select cast('<x>' + replace(A.Consultant_Contacted,' ','</x><x>')+'</x>' as xml) as n) X
             ) B

返回

Last_Name   First_Name
Name        Sample2
Sample      Name

答案 1 :(得分:1)

您还可以得到所需的结果

DECLARE 
    @stm nvarchar(max),
    @err int
SET @stm = N''

SELECT @stm = @stm + CONCAT(
         'UNION ALL ',
        'SELECT ''', 
        sysobjects.name, 
        ''' AS TableName, COUNT(*) AS RecordCount ',
        'FROM [',
        sysobjects.name,
        '] WHERE ',
        syscolumns.name,
        ' = 123 HAVING COUNT(*) > 0 ')
    FROM sysobjects 
    INNER JOIN syscolumns on sysobjects.id = syscolumns.id
    WHERE (sysobjects.xtype = 'U') AND (syscolumns.name = 'person_ID')

SET @stm = STUFF(@stm, 1, 10, '')
PRINT @stm

EXEC @err = sp_executesql @stm
IF @err = 0 
    PRINT 'OK'
ELSE 
    PRINT 'Error'