IT:AD:SQL Server:HowTo:SQL:Functions/String Functions

Summary

Easily – as long as you remember a couple of points:

  • stick with vartypes that can implicitly be converted to varchar or nvarchar (text and ntext values need to be CONVERTed first).
  • They are 1-indexed (unlike C#).
  • DATALENGTH returns the length of the string in bytes, including trailing. spaces. LEN returns the length in characters, excluding trailing spaces
  • Amazingly enough, there is no TRIM – you have to LTRIM(RTRIM(val))…

SELECT 
LEFT ('Paul', 3), -- 'Pau'
LEFT ('Paul', 10), -- 'Paul'
RIGHT ('Paul', 3), -- 'ual'
SUBSTRING('Peter', 2,2), --'et'
LTRIM (' Me '), --'Me '
RTRIM (' Me '), -- ' Me'

//Watch out for how LEN works (it's RTRIM'ed first).
LEN ('Me '), -- 2 ...wow!!
LEN (' Me '), -- 3 ....wow!
LEN (N' Me '), -- 6 ...wow!
DATALENGTH(' Me '), -- 4 
DATALENGTH(N,' Me '), -- 8
LOWER ('Me'), --'me'
UPPER ('Me')  --'ME'

-- note that Substring is 1 indexed, unlike C#.

REPLACE

Finally, and most importantly sometimes, REPLACE

Note: Remember that for TEXT/NTEXT Columns you have to convert columns out of being TEXT/NTEXT to be able to use the method, and then convert it back to the original column Type:

UPDATE Blog_Entries
SET Entry =
CAST(REPLACE(CAST(Entry AS NVARCHAR(max)),'FindMe','') AS NTEXT)
WHERE Entry LIKE
'%FindMe%';

  • /home/skysigal/public_html/data/pages/it/ad/sql_server/howto/sql/functions_string_functions.txt
  • Last modified: 2023/11/04 02:28
  • by 127.0.0.1