Commonly use sql function Part II

String Functions

Đôi khi một số hàm String rất tiện dụng. Hãy thảo luận về chúng từng cái một.

ASCII()

Trả về giá trị mã ASCII của ký tự ngoài cùng bên trái của biểu thức ký tự.
Syntax
ASCII ( character_expression ) 
Arguments: character_expression : Là một biểu thức của kiểu char hoặc varchar.
Return Types: Int 
Example 
SELECT ASCII('A')  

SET TEXTSIZE 0
SET NOCOUNT ON
-- Create the variables for the current character string position 
-- and for the character string.
DECLARE @position int, @string char(15)
-- Initialize the variables.
SET @position = 1
SET @string = 'The codeProject'
WHILE @position <= DATALENGTH(@string)
   BEGIN
   SELECT ASCII(SUBSTRING(@string, @position, 1)),
      CHAR(ASCII(SUBSTRING(@string, @position, 1)))
    SET @position = @position + 1
   END
SET NOCOUNT OFF
Output:
-----------
65
----------- ----
84          T
----------- ----
104         h
----------- ----
101         e
----------- ----
and so on..... 
CHAR()  
Chuyển đổi mã int ASCII thành ký tự.
Syntax  
CHAR ( integer_expression ) 
Arguments: integer_expression: Là một số nguyên từ 0 đến 255. NULL được trả về nếu biểu thức số nguyên không nằm trong phạm vi này.
Return Types:  character 
Example 
SET TEXTSIZE 0
SET NOCOUNT ON
DECLARE @intCounter int
SET @intCounter = 0

WHILE (@intCounter<= 255)
 BEGIN
  SELECT 'CHAR - ' + CHAR(@intCounter) + '. ASCII - ' + CONVERT(VARCHAR,@intCounter) 
  SET @intCounter = @intCounter + 1
 END


SET NOCOUNT OFF
Output:
CHAR - !. ASCII - 33
------------------------------------------------
CHAR - ". ASCII - 34
------------------------------------------------
CHAR - #. ASCII - 35
------------------------------------------------
CHAR - $. ASCII - 36
------------------------------------------------
CHAR - %. ASCII - 37
------------------------------------------------
CHAR - &. ASCII - 38
------------------------------------------------
CHAR - '. ASCII - 39
------------------------------------------------
CHAR - (. ASCII - 40
------------------------------------------------

and so on.....   

NCHAR() 

Trả về một ký tự unicode đại diện cho một số được truyền dưới dạng tham số.
Syntax 
NCHAR ( integer_expression )  
Return Types:  character 
Example : 
SELECT NCHAR(97
OutPut
This will return the leter "a"

DIFFERENCE()

Trả về một giá trị nguyên cho biết sự khác biệt giữa các giá trị SOUNDEX của hai biểu thức ký tự.
Syntax
DIFFERENCE ( character_expression , character_expression )
Arguments:character_expression: Là biểu thức của kiểu char hoặc varchar. character_expression cũng có thể là loại văn bản; tuy nhiên, chỉ 8.000 byte đầu tiên là đáng kể.
Return Types:  Int
Example :
USE AdventureWorks;
GO
-- Returns a DIFFERENCE value of 4, the least possible difference.
SELECT SOUNDEX('Green'), SOUNDEX('Greene'), DIFFERENCE('Green','Greene');
GO
-- Returns a DIFFERENCE value of 0, the highest possible difference.
SELECT SOUNDEX('Blotchet-Halls'), SOUNDEX('Greene'), DIFFERENCE('Blotchet-Halls', 'Greene');
GO
Output:
----- ----- ----------- 
G650  G650  4           

(1 row(s) affected)
                        
----- ----- ----------- 
B432  G650  0           

(1 row(s) affected)

LEFT() 

Trả về hầu hết các ký tự bên trái của một chuỗi.
Syntax
LEFT(string, length
string
Chỉ định chuỗi để lấy các ký tự bên trái nhất.

length
Chỉ định số lượng ký tự để có được
Example :
SELECT LEFT('Marufuzzaman',5)  
OutPut
Maruf

RIGHT()

Trả về đúng hầu hết các ký tự của một chuỗi.
Syntax  
RIGHT(string, length
string
Chỉ định chuỗi để lấy các ký tự bên trái nhất.

length
Chỉ định số lượng ký tự để có được.
Example :
SELECT RIGHT('Md. Marufuzzaman',12)  
OutPut
Marufuzzaman 

LTRIM() 

Trả về một biểu thức ký tự sau khi nó loại bỏ khoảng trống hàng đầu.
Example :
SELECT LTRIM('   Md. Marufuzzaman') 
OutPut
Md. Marufuzzaman

RTRIM()

Trả về một chuỗi ký tự sau khi cắt tất cả các khoảng trống theo sau.
Example : 
SELECT RTRIM('Md. Marufuzzaman    ') 
OutPut
Md. Marufuzzaman

REPLACE() 

Trả về một chuỗi với tất cả các thể hiện của một chuỗi con được thay thế bởi một chuỗi con khác
Syntax
REPLACE(find, replace, string)
Find
Chỉ định chuỗi chứa chuỗi con để thay thế tất cả các phiên bản của chuỗi khác.

Replace
Chỉ định chuỗi con để xác định vị trí.

String
Chỉ định chuỗi con để thay thế chuỗi con được định vị.

Example :
SELECT REPLACE('The codeProject is ?.','?', 'your development resource')
OutPut:
The codeProject is your development resource.

QUOTNAME()

Returns a Unicode string with the delimiters added to make the input string a valid Microsoft SQL Server delimited identifier.
Syntax
QUOTENAME ( 'character_string' [ , 'quote_character' ] )  
Arguments
' character_string '
Is a string of Unicode character data. character_string is sysname and is limited to 128 characters. Inputs greater than 128 characters return NULL.

' quote_character '
Is a one-character string to use as the delimiter. Can be a single quotation mark ( ' ), a left or right bracket ( [ ] ), or a double quotation mark ( " ). If quote_character is not specified, brackets are used.

Return Typesnvarchar(258)

Examples :
The following example takes the character string abc[]def and uses the [ and ] characters to create a valid SQL Server delimited identifier.

SELECT QUOTENAME('abc[]def')
OutPut:
[abc[]]def] 

REVERSE()

Returns a character expression in reverse order. 
Example :
SELECT REVERSE('namazzufuraM .dM')
Output: 
Md. Marufuzzaman 

CHARINDEX

CharIndex trả về lần xuất hiện đầu tiên của một chuỗi hoặc các ký tự trong một chuỗi khác. Định dạng của Char Index được đưa ra dưới đây:
CHARINDEX
( expression1 , expression2 [ , start_location
] )

Here expression1 is the string of characters to be found within expression2. So if you want to search ij within the word Abhijit, we will use ij as expression1 and Abhijit as expression2start_location is an optional integer argument which identifies the position from where the string will be searched. Now let us look into some examples :
SELECT CHARINDEX('SQL', 'Microsoft SQL Server') 
OUTPUT:
11

Vì vậy, nó sẽ bắt đầu từ 1 và tiếp tục tìm kiếm cho đến khi tìm thấy tổng phần tử chuỗi được tìm kiếm và trả về vị trí đầu tiên. Kết quả sẽ là 0 nếu không tìm thấy chuỗi tìm kiếm.

Chúng ta cũng có thể đề cập đến Start_Location của chuỗi cần tìm kiếm.

EXAMPLE:
SELECT CHARINDEX('SQL', 'Microsoft SQL server has a great SQL Engine',12)
Vì vậy, trong ví dụ trên, chúng ta có thể có Đầu ra là 34 khi chúng ta chỉ định StartLocation là 12, lớn hơn vị trí SQL ban đầu (11).

PATINDEX

PatIndex được sử dụng để tìm kiếm một mẫu trong một biểu thức. Sự khác biệt giữa CharIndex và Pat Index là sau này cho phép các ký tự WildCard.
PATINDEX
( '%pattern%' , expression)
Ở đây, đối số đầu tiên có một mẫu có các ký tự đại diện như '%' (meaning any string) or '_' (meaning any character).

For Example
PATINDEX('%BC%','ABCD')

Output:  
2

Another flexibility of PATINDEX is that you can specify a number of characters allowed within the Pattern. Say you want to find all of the records that contain the words "Bread", or "bread" in a string, You can use the following :
SELECT PATINDEX('%[b,B]read%', 'Tommy loves Bread') 
In this example, we mentioned both b and B in square brackets. The Result will be 13 which is same if we have searched in 'Tommy loves bread'.

LEN

Len is a function which returns the length of a string. This is the most common and simplest function that everyone use. Len Function excludes trailing blank spaces.
SELECT LEN('ABHISHEK IS WRITING THIS')
This will output 24, it is same when we write LEN('ABHISHEK IS WRITING THIS ') as LEN doesnt take trailing spaces in count.

STUFF


Stuff is another TSql Function which is used to delete a specified length of characters within a string and replace with another set of characters. The general syntax of STUFF is as below :

STUFF(character_expression1, start, length, character_expression2)Character_Expression1 represents the string in which the stuff is to be applied. start indicates the starting position of the character in character_expression1length is the length of characters which need to be replaced. character_expression2 is the string that will be replaced to the start position.

Let us take an example :
SELECT STUFF('SQL SERVER is USEFUL',5,6,'DATABASE')
So the result will be :
SQL DATABASE is USEFUL

SUBSTRING


Substring returns the part of the string from a given characterexpression. The general syntax of Substring is as follows :

SUBSTRING(expression, start, length)
Here the function gets the string from start to length. Let us take an example below:
SELECT OUT = SUBSTRING('abcdefgh', 2, 3)
The output will be "bcd".
Note : substring also works on ntext, VARCHAR, CHAR etc.

LOWER / UPPER


Anoter simple but handy function is Lower / UPPER. The will just change case of a string expression. For Example,
SELECT UPPER('this is Lower TEXT') 

Output:
THIS IS LOWER TEXT

Nhận xét

Bài đăng phổ biến từ blog này

Material Tree

.Net secure coding guidelines

Tìm hiểm Checkbox Angular Material