开发者

Split a value in one column to two columns

I have a column in SQL that I would like to split a column into two columns on select (by a delimiter). For example, the table currently has:

---------
Mary - 16
开发者_JAVA百科

I'd like two columns as the result of the query:

--------   --------
Mary       16

Thanks for your help.


SELECT 
  left_side  = RTRIM(SUBSTRING(col, 1, CHARINDEX('->', col)-2)),
  right_side = LTRIM(SUBSTRING(col, CHARINDEX('->', col) + 2, 4000))
FROM dbo.table;

Ah, I see. | characters are column specifiers, not part of the output. Try:

SELECT 
  left_side  = LTRIM(RTRIM(SUBSTRING(col, 1, CHARINDEX('-', col)-1))),
  right_side = LTRIM(RTRIM(SUBSTRING(col, CHARINDEX('-', col) + 1, 4000)))
FROM dbo.table;


If your not worried about edge cases, something like this will work:

Declare @Var varchar(200)
SET @Var = 'Mary - 16'

SELECT LEFT(@Var, PATINDEX('%-%', @Var) - 1), Right(@Var, LEN(@Var) - PATINDEX('%-%', @Var))

Just change @Var to your field name in the query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜