我在其中一个列的数据看起来像这样的ALAN,DONALD [1234],我需要将其拆分为两列,例如Name(ALAN,DONALD),ID(1234) 我尝试了以下代码,但可以获取ID而不是名称
create table #test(NAME_ID VARCHAR(50))
INSERT INTO #TEST VALUES ('ALAN,DONALD [1234])' )
SELECT CAST (substring(NAME_ID,charindex('[',NAME_ID)+1,charindex(']',NAME_ID)-charindex('[',NAME_ID)-1) AS VARCHAR (102) ) AS MRN FROM #TEST
答案 0 :(得分:0)
您可以根据括号的索引进行操作:
SELECT
RTRIM(SUBSTRING(NAME_ID, 0, CHARINDEX('[',NAME_ID))) AS Name,
CAST (SUBSTRING(NAME_ID,CHARINDEX('[',NAME_ID)+1,CHARINDEX(']',NAME_ID)-
CHARINDEX('[',NAME_ID)-1) AS VARCHAR (102) ) AS MRN
FROM #TEST