String split in microsoft sql server

3htmauhk  于 2023-03-28  发布在  SQL Server
关注(0)|答案(3)|浏览(140)

I have to split a column and have to create two new other columns in microsoft sql server.

Input:

Output:

Could you please help me on this.

iih3973s

iih3973s1#

here is a hack using parsename

SELECT PARSENAME(REPLACE('120/20','/','.'),2) as SP, 
PARSENAME(REPLACE('120/20','/','.'),1) as DP

Output

SP DP
120 20
ipakzgxi

ipakzgxi2#

You can use ALTER to do that.

Example:

ALTER TABLE table_name
ADD column_name data_type
41zrol4v

41zrol4v3#

You can try to create computed columns in case you are not allowed or able to populate the columns on write/update:

CREATE TABLE DataSource 
(
    ID INT PRIMARY KEY
   ,BPValue VARCHAR(12)
)

GO

INSERT INTO DataSource (ID, BPValue)
VALUES (1, '123/98')
      ,(2, '118/72')
      ,(3, '97/74');

GO

ALTER TABLE DataSource
ADD Value1 AS TRY_CAST(SUBSTRING(BPValue, 0, CHARINDEX('/', BPValue)) AS INT)

ALTER TABLE DataSource
ADD Value2 AS TRY_CAST(SUBSTRING(BPValue, CHARINDEX('/', BPValue) + 1, 128) AS INT)

GO

SELECT *
FROM DataSource

Also, the columns can be materialized if you create them with the PERSISTED option. Otherwise, the computation is perform on read, which can be slow on certain cases.

The better way, is to create two separate columns and populate the data on insert/update.

The above can be done on MySQL , too. Here is the link to the official documentation.

相关问题