子查询将逗号分隔值拆分为两列

时间:2016-12-09 19:15:00

标签: sql-server sql-view

我有一个字段,有时有一个值,有时2个值用逗号分隔。我需要将值拆分为两列。我见过使用函数的解决方案,但我需要将它添加到视图中。

以下是我一直试图为第一栏做的事情

SELECT 
CASE
WHEN EXISTS(SELECT reportto FROM dbo.placement WHERE reportto like '%,%') 
THEN
(Select Substring(reportTo, 1,Charindex(',', reportTo)-1) as [Primary OTS Approver]
from placement) 
ELSE (SELECT reportto as [Primary OTS Approver] FROM dbo.placement)
END

2 个答案:

答案 0 :(得分:1)

您不需要SELECT CASE WHEN CHARINDEX(',', reportto) > 0 THEN SUBSTRING(reportto, 1, CHARINDEX(',', reportto) -1) ELSE reportto END AS [Primary OTS Approver] FROM placement; statemant中的子选择,您可以直接使用这些列:

<div class="mt-flight-input" ng-class="{'mt-dirty': value.newvalue != value.initial, 'mt-zero': value.newvalue == 0}">
  <input type="number" class="mt-input" placeholder="0" ng-show="value.isAuthoring" ng-model="value.newvalue" ng-blur="checkValue('blur', value)" ng-focus="checkValue('focus', value)">
  <input type="text" class="mt-input" placeholder="0" ng-show="!value.isAuthoring" ng-value="value.newvalue | currency:'': '0'| comma2dots" ng-click="showEditor($event, value)" ng-focus="showEditor($event, value)" readonly="readonly">
</div>

答案 1 :(得分:0)

您可以使用CROSS APPLY来降低代码复杂性并简化主SELECT语句

通过这个例子,您只需要调用一次CHARINDEX并将其重用为值&#34; P&#34;

DROP TABLE #TMP
CREATE TABLE #TMP(ID INT, Vals CHAR(100))

INSERT INTO  #TMP(VALS)
VALUES
('32')
,('31,25')
,('21,32')

SELECT
    CASE    
        WHEN P > 0 THEN SUBSTRING(VALS, 1, P -1) 
        ELSE VALS 
        END AS  [Primary OTS Approver]
FROM
    #TMP
        CROSS APPLY (SELECT CHARINDEX(',',VALS,0) P) Z