Server SQL sort by size

Source: Internet
Author: User

The following method uses the SQL function stored procedure to sort the size.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Alter function [dbo]. [udf_OrderLimitSize]
(
@ Ov NVARCHAR (30)
)
RETURNS decimal (18,6)
AS
BEGIN
-- If the length is less than or equal to 2, NULL is returned.
IF (LEN (@ Ov) <= 2)
RETURN NULL
-- Declare two variables
DECLARE @ v DECIMAL (18,6), @ n DECIMAL (18,6)

-- Determine whether the last two digits are the following units
IF (RIGHT (@ Ov, 2) not in ('TB', 'GB', 'mb', 'KB '))
RETURN NULL
-- After removing the last two digits, convert the value to the DECIMAL data type.
SET @ n = CONVERT (DECIMAL (18,6), LEFT (@ Ov, LEN (@ Ov)-2 ))
-- After the last two digits are intercepted, ISNUMERIC is used to determine whether the value is valid. If not, NULL is returned.
IF (ISNUMERIC (@ n) = 0)
RETURN NULL
-- Perform unit calculation. If a new unit exists, add it accordingly.
IF (@ Ov LIKE '% TB ')
SET @ v = @ n * 1024*1024*1024
IF (@ Ov LIKE '% G ')
SET @ v = @ n x 1024*1024
IF (@ Ov LIKE '% MB ')
SET @ v = @ n * 1024
IF (@ Ov LIKE '% kb ')
SET @ v = @ n
RETURN @ v
END

Instance

 

Create table test (id int identity (1, 1), size NVARCHAR (50 ))
GO
Insert into [test] values ('23. 5mb'), ('10gb'), ('12. 7mb'), ('8gb ')
Go
SELECT [id], [size] FROM test order by [dbo]. [udf_OrderLimitSize] ([size])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.