将字符串拆分选择SQL查询更改为更新查询

时间:2018-12-11 12:28:56

标签: sql sql-server

我正在尝试将SQL表中的列拆分为两列,其中列中的数据用“-”分隔,我设法编辑了在网上找到的查询以执行此操作。

问题是,由于它是select查询,因此仅返回要查看的数据。

如何更改此查询以更新表?

select
case when CHARINDEX('-',ProjectNumber)>0 
     then SUBSTRING(ProjectNumber,1,CHARINDEX('-',ProjectNumber)-1) 
     else ProjectNumber end ProjectNumber, 
CASE WHEN CHARINDEX('-',ProjectNumber)>0 
     THEN SUBSTRING(ProjectNumber,CHARINDEX('-',ProjectNumber)+1,len(ProjectNumber))  
     ELSE NULL END as Vessel
from dbo.Stock

编辑:

我已经尝试过:

update dbo.stock set vessel =
 case when CHARINDEX('-',ProjectNumber)>0 
 then SUBSTRING(ProjectNumber,1,CHARINDEX('-',ProjectNumber)-1) 
 else ProjectNumber end **ProjectNumber,**
CASE WHEN CHARINDEX('-',ProjectNumber)>0 
 THEN SUBSTRING(ProjectNumber,CHARINDEX('-',ProjectNumber)+1,len(ProjectNumber))  
 ELSE NULL END as Vessel

但这告诉我我在ProjectNumber附近遇到语法错误,这是我给星号加注的语法错误。

1 个答案:

答案 0 :(得分:0)

为什么不使用STRING_SPLIT函数? (https://docs.microsoft.com/es-es/sql/t-sql/functions/string-split-transact-sql?view=sql-server-2017#examples):

UPDATE dbo.Stock
SET vessel = id1,
    vessel2 = id2
FROM (
 SELECT id, 
  (SELECT TOP 1 value as val 
  FROM STRING_SPLIT(id, '-')  
  ORDER BY (ROW_NUMBER() OVER(ORDER BY 1 ASC)) ASC
  ) AS id1, 
  (SELECT TOP 1 value as val 
  FROM STRING_SPLIT(id, '-')  
  ORDER BY (ROW_NUMBER() OVER(ORDER BY 1 ASC)) DESC
  ) AS id2
 FROM dbo.Stock
) A inner join dbo.Stock  B
ON A.id = B.id;