How to use SQL SERVER ParseName to separate strings

PARSENAME (parseName)
returns the specified part of the object name. The object parts that can be retrieved are the object name, the owner name, and the description PARSENAME function does not indicate whether the object with the specified name exists, but only returns the specified part of the given object name. Otherwise NULL.

语法
PARSENAME ( 'object_name' , object_piece )

illustrate

According to "." as a separator, quickly obtain the decomposed part, which can only be split into 4 fields at most.

'object_name'

The name of the object whose specified part is to be retrieved. The data type of object_name  is  sysname . This parameter is an optional qualified object name. If all parts of the object name are qualified, the name can contain four parts: server name, database name, owner name, and object name.

object_piece

The part of the object to return. The data type of object_piece  is  an int  value, which can be the following values:

1 = object name

2 = schema name

3 = database name

4 = server name

The PARSENAME function does not indicate whether an object with the specified name exists. PARSENAME returns only the specified part of the specified object name.


Example 1:

Select parsename('A,B,C.C,E.F',2)

 Example 2:

Replace '.' because parsename only recognizes '.' 

DECLARE @PA TABLE
(COL VARCHAR(80))

INSERT INTO @PA
SELECT'123_12_124'UNION ALL   
SELECT'1234_125_1243' UNION ALL   
SELECT'12345_1245_12435' UNION ALL   
SELECT'123456_12456_124356' 

SELECT COL, COL1 =PARSENAME(REPLACE(COL,'_','.'),3),
       COL2 =PARSENAME(REPLACE(COL,'_','.'),2),
       COL3 =PARSENAME(REPLACE(COL,'_','.'),1)
FROM @PA

result:

Example 3: Mainly used for IP address segmentation

DECLARE @ip NVARCHAR(50) = '192.168.1.1';
SELECT
    PARSENAME(@ip, 1) AS col1,
    PARSENAME(@ip, 2) AS col2,
    PARSENAME(@ip, 3) AS col3,
    PARSENAME(@ip, 4) AS col4;

result:

 

Example 4: Convert to standard IPv4 format


CREATE  FUNCTION  [dbo].[svf_ConvertToStandardIPv4]
(
    @IP NVARCHAR(MAX)
) 
RETURNS NVARCHAR(MAX)
AS
BEGIN
    RETURN  REPLICATE('0',3 - LEN(PARSENAME(@IP,4))) + PARSENAME(@IP,4) + '.' +
            REPLICATE('0',3 - LEN(PARSENAME(@IP,3))) + PARSENAME(@IP,3) + '.' +
            REPLICATE('0',3 - LEN(PARSENAME(@IP,2))) + PARSENAME(@IP,2) + '.' +
            REPLICATE('0',3 - LEN(PARSENAME(@IP,1))) + PARSENAME(@IP,1)    
END
go
SELECT  [dbo].[svf_ConvertToStandardIPv4]  ('8.8.8.8')

 Mainly used for ip address resolution

It should be noted that it can only be split into 4 fields at most.

For others, you can replace it with REPLACE

Another idea: write a function  

Use SUBSTRING and CHARINDEX to intercept and split fields according to specific segmentation symbols

Guess you like

Origin blog.csdn.net/simon4055/article/details/130064536