sql server中的子字符串

时间:2015-09-07 04:26:43

标签: sql-server sql-server-2008

我有格式的字符串。 (例如902.5)
需要在sql server 2008中将其拆分并收集到单独的变量中。

    DECLARE  
       @Core VARCHAR(10)='902.5',  
       @OrgNumber VARCHAR(6) = NULL,  
       @DeptNumber VARCHAR(2) = NULL

        IF (NULLIF(@Core, '')) IS NOT NULL
        BEGIN
             SELECT @OrgNumber =SUBSTRING(@Core, 1, CHARINDEX('.', @Core) - 1),
                   @DeptNumber =SUBSTRING(@Core, CHARINDEX('.', @Core) + 1, LEN(@Core))

             SELECT @OrgNumber = upper(nullif(ltrim(nullif(rtrim(@OrgNumber ), '')), '')), 
@DeptNumber = nullif(ltrim(nullif(rtrim(@DeptNumber ), '')), '')  
        END

然而,这并不能处理仅包含组织参考(没有部门参考)的情况,例如902
如何在同一语句中优雅地处理案例?

2 个答案:

答案 0 :(得分:2)

使用$('#mybutton').click(function () { $.ajax({ url: 'About.aspx', dataType: 'text', type: "GET", success: function(data) { var result = $.trim(data); // Hide all $('div#graphic img').hide(); // Show matched one $('#gate' + result).show(); } }); }); 功能

PARSENAME

答案 1 :(得分:0)

更新了您的查询。另请注意,IF (NULLIF(@Core, '')) IS NOT NULL不正确。

 DECLARE @Core       VARCHAR(10)='902', 
        @OrgNumber  VARCHAR(6) = NULL, 
        @DeptNumber VARCHAR(2) = NULL 

IF @Core IS NOT NULL 
  BEGIN 
      SELECT @OrgNumber = CASE 
                            WHEN Charindex('.', @Core) > 0 THEN 
                            Substring(@Core, 1, Charindex('.', @Core) 
                                                - 1) 
                            ELSE Substring(@Core, 1, Len(@Core)) 
                          END, 
             @DeptNumber = CASE 
                             WHEN Charindex('.', @Core) > 0 THEN 
                             Substring(@Core, 
                             Charindex('.', @Core) + 1 
                             , Len(@Core)) 
                             ELSE NULL 
                           END 

      SELECT @OrgNumber = Upper(NULLIF(Ltrim(NULLIF(Rtrim(@OrgNumber), '')), '') 
                          ), 
             @DeptNumber = NULLIF(Ltrim(NULLIF(Rtrim(@DeptNumber), '')), '') 
  END 

SELECT @OrgNumber, 
       @DeptNumber